Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain this algorithm to get all permutations of a String

The following code generates all the permutations for a string:

def permutations(word):
    if len(word)<=1:
        return [word]

    #get all permutations of length N-1
    perms=permutations(word[1:])
    char=word[0]
    result=[]
    #iterate over all permutations of length N-1
    for perm in perms:
        #insert the character into every possible location
        for i in range(len(perm)+1):
            result.append(perm[:i] + char + perm[i:])
    return result

Can you explain how it works? I don't understand the recursion.

like image 736
gran_profaci Avatar asked Dec 23 '12 04:12

gran_profaci


People also ask

How do you find the permutation of a string?

We can find the count without finding all permutation. Idea is to find all the characters that is getting repeated, i.e., frequency of all the character. Then, we divide the factorial of the length of string by multiplication of factorial of frequency of characters.

What is a permutation algorithm?

This algorithm is based on swapping elements to generate the permutations. It produces every possible permutation of these elements exactly once. This method is a systematic algorithm, which at each step chooses a pair of elements to switch in order to generate new permutations.


1 Answers

The algorithm is:

  • Remove the first letter
  • Find all the permutations of the remaining letters (recursive step)
  • Reinsert the letter that was removed in every possible location.

The base case for the recursion is a single letter. There is only one way to permute a single letter.

Worked example

Imagine the start word is bar.

  • First remove the b.
  • Find the permuatations of ar. This gives ar and ra.
  • For each of those words, put the b in every location:
    • ar -> bar, abr, arb
    • ra -> bra, rba, rab
like image 135
Mark Byers Avatar answered Oct 17 '22 10:10

Mark Byers