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 ?
itertools.permutationsdoes the work for you :)