I try to implement permutation algorithm. It works well.
But my questions about recursion in this algorithm
Permutation function:
def permutations(word):
how and why it continue to work after return statement?
if len(word) == 1:
return [word]
how it goes back if last perms == ['3'] how it back to ['23'] from ['3']?
perms = permutations(word[1:])
char = word[0]
result = []
for perm in perms:
for i in range(len(perm) 1):
result.append(perm[:i] char perm[i:])
return result
CodePudding user response:
I understood. Recursion based on stack. That is why it continue to execute after return statement.
CodePudding user response:
- I was testing your solution and I don't understand why you say it doesn't stop with the return because it stops me in the base case as it should
- The problem with that part of the code is when you use
perm[i:]
instead ofperm[i-1:
since you need also the first element (that's why you get just 3 instead of 23 and 32)
So it should look something like this:
result.append(perm[:i] char perm[i-1:])