I am trying to code the String permutation problem. Instead of string I have a list of integers like [1,2,3]. I have to print out all possible permutations of the list. However, there's some issue with my code that I'm not able to figure out. Somehow, the line if not in words
in the base case hits only once. I'm trying to figure this out from the past one hour. Any help would be appreciated!. TIA
Here's the code
words = list()
def permute(nums):
if len(nums) == 0:
return None
l = 0
r = len(nums)
permute_helper(nums,0,r)
def permute_helper(nums,start,end):
current = 0
if start == end-1:
if not nums in words:
print 'appended'
words.append(nums)
else:
for current in range(start,end):
temp = nums[start]
nums[start] = nums[current]
nums[current] = temp
#Recursive call
permute_helper(nums,start+1,end)
temp = nums[start]
nums[start] = nums[current]
nums[current] = temp
permute([1,2,3])
print words
The bug is that you keep modifying the same list nums
so you end up with only one copy that was modified but the modifications were not recorded.
Change:
words.append(nums)
to:
words.append(nums[:])
which will create a copy of nums
and "freeze" it current state.
Comment: You can do the swap in a more pythonic way, instead of:
temp = nums[start]
nums[start] = nums[current]
nums[current] = temp
do:
nums[start], nums[current] = nums[current], nums[start]