0
def permutationString(word):
    print('word', word)
    result = []

    if len(word) == 0:
        result.append('')
        return result

    for i in range(len(word)):
        before = word[0 : i]
        after = word[i + 1 :]
        print('before',before)
        print('after', after)
        partials = permutationString(before + after)
        print(partials)
        for s in partials:
            result.append(word[i] + s)

    return result

This is my solution for generating a permutation for a given string.

For an input abc, it gives me ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] which seems to be correct.

My question is, I don't really understand how the magic works. The code itself is pretty intuitive; we just try each character as the first character and then append the permutations.

But I really don't get how the partials is generated and I am not sure how the solution does not work when we do not do result.append('') when the word is empty.

Is there an intuitive explanation of how the magic works?

smci
  • 32,567
  • 20
  • 113
  • 146
Dawn17
  • 7,825
  • 16
  • 57
  • 118
  • a) Ideally we to handle permutations of empyt word too so conditional is necesseary, b) if permutationString('') return empty set, then the inner loop is empty for one letter words, then for two lettern words, and so on. c) if you dislike append shorten the conditional to `if not word: return[""]` – Serge Nov 20 '18 at 15:48

1 Answers1

1

I have a full lengthy answer here.

The shorter answer is that there's only one way to write a sequence with no elements. That is the empty sequence. So the list with all the permutations of '' is [''].

Suppose you got that wrong and return [] instead, that is, no solutions. What would happen then?

Well, in the inductive case, as you said, you try each element as the first, and put it in front of the solutions for permutations without that element. So consider a sequence with just one element 'x'. You are going to put x in front of all the solutions for ''. If permutations of '' returned [], that is an empty list with no solutions, then you would have no solutions to put x in front of. It returns [''] though, so you're going to put 'x' in front of that one solution ''.

Bonus

Once you think you got it, you may want to try another similar algorithm for calculating permutations.

Try to build all permutations of word selecting only the first element word[0] at each recursive step, and somehow 'combining' it with the solutions for the permutations of word[1:].