I have implemented a pretty basic algorithm to print permutations of a list in python. However, I am unable to figure out the reason for the behavior of a property of an object. Here's the code :
class Solution:
def permute(self, A):
self.ans = []
self.generate_perm(list(A))
return self.ans
def generate_perm(self, A, k=0):
#print A, k
#print self.ans
if k == len(A):
self.process(A)
else:
for i in xrange(k, len(A)):
A[k], A[i] = A[i], A[k]
self.generate_perm(A, k+1)
A[k], A[i] = A[i], A[k]
def process(self,A):
print A
self.ans.append(A)
sol = Solution()
print sol.permute([1,2,3])
The output of the above snippet is :
[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]]
I was expecting the append method to add the input to process()
, but somehow it just duplicates the last appended item to the number of terms existing in list + adds one more.
I think it should be fairly direct.