I'm having difficulty creating a 2D list of permutations. Here is a minimal code to reproduce the problem
class Solution:
def permute(self, A):
A = sorted(A)
print A
A_out = []
A_out.append(A)
for iter0 in range(4):
A[0] = A[0] + 1
print A
A_out.append(A)
return A_out
sol = Solution()
A = [1, 2, 3]
print sol.permute(A)
For this particular input(1, 2, 3) the output is
[1, 2, 3]
[2, 2, 3]
[3, 2, 3]
[4, 2, 3]
[5, 2, 3]
[[5, 2, 3], [5, 2, 3], [5, 2, 3], [5, 2, 3], [5, 2, 3]]
but the desired output is
[1, 2, 3]
[2, 2, 3]
[3, 2, 3]
[4, 2, 3]
[5, 2, 3]
[[1, 2, 3], [2, 2, 3], [3, 2, 3], [4, 2, 3], [5, 2, 3]]
I think it has something to do deep copy/ shallow copy thing but I am not sure how to correct this as I am not very familiar with Python. How can I fix it?
It is indeed about shallow copies. The list A
you keep appending always refers to the same value. This is related to the mutability of lists in Python.
You need to append a new copy of the list each time to make them independent of each other. You can do that using the slice operator [:]
because it creates a new copy of the list. So you can just use it when calling append
def permute(self, A):
A = sorted(A)
print A
A_out = []
A_out.append(A[:])
while (self.checkVal(A) != -1) :
A = self.nextState(A,self.checkVal(A))
print A
A_out.append(A[:])
return A_out