On the problem of python Total permutation

def permutations(a):
    result = []
    helper(a, result, 0, len(a))
    return result


def helper(a, result, lo, hi):
    if lo == hi:
        print(a)
        result.append(a)
    else:
        cursor = lo
        for i in range(lo, hi):
            a[cursor], a[i] = a[i], a[cursor]
            helper(a, result, lo + 1, hi)
            a[cursor], a[i] = a[i], a[cursor]


if __name__ == "__main__":
    a = [1, 2, 3]
    re = permutations(a)
    print(re)

output:

clipboard.png

I really can"t figure out why all the values in result are [1, 2, 2, 3]

.
Mar.20,2021

because you are operating on the same object, you should generate a new object when you save the result, like this

        -sharp result.append(a)
        result.append(tuple(a))

by the way, Python has its own permutation and combination function

from itertools import combinations  -sharp 
from itertools import combinations_with_replacement  -sharp 
from itertools import product  -sharp 
from itertools import permutations  -sharp 
Menu