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
I understood. Recursion based on stack. That is why it continue to execute after return statement.
perm[i:]
instead of perm[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:])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.