简体   繁体   中英

python permutations algorithm based on recursion

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.

  1. 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
  2. The problem with that part of the code is when you use 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM