0

The below code returns all possible permutations of the numbers provided.

class Solution:

  def permute(self, numbers, start, result):
        if start == len(numbers):
            print(numbers)
            result.append(numbers[:])
            return
        for i in range(start, len(numbers)):
            numbers[start], numbers[i] = numbers[i], numbers[start]
            self.permute(numbers, start + 1, result)
            numbers[start], numbers[i] = numbers[i], numbers[start]

  def solution(self, numbers):
        result = []
        if not numbers or len(numbers) == 0:
            return numbers
        self.permute(numbers, 0, result)
        return result

res1 = Solution().solution([1, 2, 3])
print(res1)

The final output for this instance will be

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

but when I slightly modify the permute function, the output is completely different

def permute(self, numbers, start, result):
        if start == len(numbers):
            print(numbers)
            result.append(numbers) #changing this line
            return
        for i in range(start, len(numbers)):
            numbers[start], numbers[i] = numbers[i], numbers[start]
            self.permute(numbers, start + 1, result)
            numbers[start], numbers[i] = numbers[i], numbers[start]

which gives the output

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

The program works when I use

result.append([x for x in numbers])

or

result.append(numbers[:])

but not when I use

result.append(numbers)

Can someone help me understand as to why this is happening ?

2
  • As in Karoly Horvath answer , when you do numbers[:] it creates a new array for you. Commented May 23, 2016 at 14:53
  • FYI: itertools.permutations does the work for you :) Commented May 23, 2016 at 14:58

1 Answer 1

2

If you don't create a copy of the object with the techniques you've described, you put the same object in the list again and again.

Here's a short example to illustrate the issue:

>>> a=[1,2]
>>> b=[a,a]
>>> a.append(3)
>>> b               #   [[1, 2, 3], [1, 2, 3]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick reply :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.