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?