0

I am writing a function to get all of the permutations for a given input:

e.g. Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

def permute(nums):
    permutation_set = []
    pointer_stand = 0
    pointer_runner = 0
    permutation_set.append(nums)

    while pointer_stand < len(nums)-1:

        while pointer_runner < len(nums)-1:
            
            pointer_runner +=1
            nums[pointer_stand], nums[pointer_runner] = nums[pointer_runner], nums[pointer_stand]
            permutation_set.append(nums)

        pointer_stand += 1
        pointer_runner = pointer_stand


    return permutation_set

I can't seem to see where I am going wrong, but the output I am getting is [[3,2,1],[3,2,1],[3,2,1],[3,2,1],[3,2,1]]

Any idea where the code is wrong? Because when I write it out, it should work! Thanks

P.S. I know the code above doesn't produce all of the permutations, I still need to 'rotate' the original input to get the rest of the permutations, but for now I am stuck swapping each index, as per my question above. Thanks

heio fhow
  • 19
  • 3
  • I'm not sure why your code is not working but have you tried using the library random instead? – Noa Even May 15 '21 at 13:44
  • You can use permutation function directly available in python. Just import it from itertools. – Vishwajit Rahatal May 15 '21 at 13:44
  • 4
    Lists, like other containers in Python, store references to objects. You modify the same object "nums" and append multiple references to "permutation_set". Instead create always a shallow copy with "nums[:]" and append it. – Michael Butscher May 15 '21 at 13:45
  • [This](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list) might solve your issue – Orbital May 15 '21 at 13:53
  • Thanks Orbital and @MichaelButscher. Michael, I totally see what you are saying- lesson learned. – heio fhow May 16 '21 at 08:31

0 Answers0