0

My python code is just try to print all the permutation of a given list (num in my code). Here is my code

#!/usr/bin/python3    

        def permutation(list_num, checked_length, length):
            if checked_length == length - 1:
                print(list_num)
            else:
                for i in range(checked_length, length):
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]
                    permutation(list_num, checked_length + 1, length)
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]


        num = [1, 2, 3]
        permutation(num, 0, len(num))

It gives out the result as i want to

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

but when i try to change just a little. I want the output of that code to store in Answer_list. I got this unexpected result:

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

Here is my code that got the result:

        #!/usr/bin/python3
    Answer_list = []
    def permutation(list_num, checked_length, length):
            if checked_length == length - 1:
                Answer_list.append(list_num) # change here
            else:
                for i in range(checked_length, length):
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]
                    permutation(list_num, checked_length + 1, length)
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]


num = [1, 2, 3]
permutation(num, 0, len(num))
print(Answer_list)
haxerl
  • 111
  • 1
  • 6

0 Answers0