1

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
CodeSsscala
  • 729
  • 3
  • 11
  • 23

2 Answers2

1

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]
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

You're appending the same list each time. No wonder it's already there (in words).

In other words, you are not collecting each different permutation, but a reference to nums. So, subsequent permutations are reflected in words. That's the plague of mutability.

One solution is to make a copy of the current permutation:

words.append(nums[:])

By the way, a pythonic swap is:

a, b = b, a   # no need for tmp

Also, there is no need to reset current.

YvesgereY
  • 3,778
  • 1
  • 20
  • 19