top of page

GET PERMUTATIONS

  • Writer: MHK
    MHK
  • Aug 23, 2020
  • 1 min read

def get_permutations(sequence):
    '''
    Enumerating all permutations of a given string using recursion
    '''
    permutation_list=[]
    third=[]
    # Traveler function is a helper function I designed that I used 
    # afterwards in my code.
    def traveler(string, element):
        string=list(string)
        zero=0
        new_list=[]
        list_result=[]
        while zero<=len(string):
            string.insert(zero, element)
            string2=string[:]
            string2=''.join(string2)
            list_result.append(string2)
            string.remove(element)
            zero+=1
            for t in list_result:
                t=''.join(t)
                new_list.append(t)
            return new_list
    #BASE CASE
    if len(sequence)==1:
        permutation_list.append(sequence)
        return((permutation_list))
    else:
        k=sequence[0]
        sequence=list(sequence)
        sequence.remove(k)
        sequence=''.join(sequence)
        x=get_permutations(sequence)
        for t in x:
            w=traveler(t,k)
            third.append(w)
        for s in third:
            for p in s:
                permutation_list.append(p)
        #and lastly we have a caution to prevent returning the same 
        #element in the permutation_list.
        for p in permutation_list:
            while permutation_list.count(p)>1:
                permutation_list.remove(p)
        return permutation_list
                
        
    

And lastly, there are some outputs of this function I wanted to share in case if you want to test it:

EX1:


sequence='asd'
print(get_permutations(sequence))
#OUTPUT:['asd', 'sad', 'sda', 'ads', 'das', 'dsa']


EX2:


sequence='aaaa'
print(get_permutations(sequence))
#OUTPUT: ['aaaa']

EX3:



sequence='farm'
print(get_permutations(sequence))
#OUTPUT: ['farm', 'afrm', 'arfm', 'armf', 'fram', 'rfam', 'rafm', 'ramf', 'frma', 'rfma', 'rmfa', 'rmaf', 'famr', 'afmr', 'amfr', 'amrf', 'fmar', 'mfar', 'mafr', 'marf', 'fmra', 'mfra', 'mrfa', 'mraf']

Комментарии


Created By Root Team 

  • Facebook
  • Twitter
  • YouTube
  • Pinterest
  • Tumblr Social Icon
  • Instagram
bottom of page