I was trying to translate my code to python to print all possible permutation of a list. My code goes below:
def helper(A, l, r, ans):
if l == r:
print(A)
ans.append(A)
else:
for i in range(l, r + 1):
A[l], A[i] = A[i], A[l]
helper(A, l+1, r, ans)
A[l], A[i] = A[i], A[l]
def permute(A):
ans = []
helper(A, 0, len(A)-1, ans)
print(ans)
permute([1, 2, 3])
Strangely I get this as output:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
What is going on here?