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?