Python joins an object

I implemented a fairly simple algorithm for printing list permutations in python. However, I cannot understand the reason for the behavior of the property of the object. Here is 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:

[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 expected the append method to add input to process(), but somehow it just duplicates the last item added by the number of terms that exist in the + list, adds another one.

I think it should be pretty straight forward.

+4
source share

All Articles