0

I'm trying to write a program that, given a number n, would return all permutations of said number. I'm having trouble filling the list properly.

Here's my code so far:

import math

def permute(a, l, r, p):
if l == r:
    p.append(a)
    print(a)
else:
    for i in range(l, r + 1):
        a[l], a[i] = a[i], a[l]
        permute(a, l + 1, r, p)
        a[l], a[i] = a[i], a[l]  # Backtrack
return p


n = 1347
size = math.floor(math.log(n, 10))

a = list(map(int, str(n)))

permutations = permute(a, 0, size, [])

print("------")
print(permutations)

Here' my output:

[1, 3, 4, 7]
[1, 3, 7, 4]
[1, 4, 3, 7]
[1, 4, 7, 3]
[1, 7, 4, 3]
[1, 7, 3, 4]
[3, 1, 4, 7]
[3, 1, 7, 4]
[3, 4, 1, 7]
[3, 4, 7, 1]
[3, 7, 4, 1]
[3, 7, 1, 4]
[4, 3, 1, 7]
[4, 3, 7, 1]
[4, 1, 3, 7]
[4, 1, 7, 3]
[4, 7, 1, 3]
[4, 7, 3, 1]
[7, 3, 4, 1]
[7, 3, 1, 4]
[7, 4, 3, 1]
[7, 4, 1, 3]
[7, 1, 4, 3]
[7, 1, 3, 4]
------
[[1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7], [1, 3, 4, 7]]

For some reason printing a is fine but appending it to p is not working properly. My guess is that it has to do with scope.

Edit: Changing p.append(a) to p.append(a[:]) fixed the problem, but can someone explain to me why the print() prints the right permutations while the appending append the same permutation to the array?

YSA
  • 799
  • 1
  • 12
  • 30
  • 1
    You need to copy the current permutation when you append it to result list, otherwise you'll just have multiple copies of the same result. – niemmi Feb 01 '17 at 03:26
  • Modifying this line `p.append(a[:])` worked! Can you please explain to me why that is the case? – YSA Feb 01 '17 at 03:44
  • 1
    You were appending the same `list` over and over again. Then when you change that `list` you obviously see the changes everywhere it's referred to. See the duplicate question for detailed answer. – niemmi Feb 01 '17 at 03:47
  • I see, but why does the `print()` work properly? Shouldn't it have printed the same `list` over and over again too? – YSA Feb 01 '17 at 03:50
  • 2
    It prints the same list but since you mutate that list between `print` calls you see different output. At the final iteration of the loop you mutate the list back to its' original state which is then reflected by the `print` call after the loop. – niemmi Feb 01 '17 at 03:54

0 Answers0