Computer >> Computer tutorials >  >> Programming >> Python

Permutations in Python


Suppose we have a collection of distinct integers; we have to find all possible permutations. So if the array is like [2,1,3], then the result will be [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

To solve this, we will follow these steps −

  • We will use the recursive approach, this will make the list, start, curr and res
  • if start > length of list – 1, then add curr into the res, and return
  • for i in range start to length of given list – 1
    • swap the elements of list present at index start and (start + (i – start))
    • permutation(list, start + 1, curr + [list[start]], res)
    • swap the elements of list present at index start and (start + (i – start))
    • initially call the permutation(arr, 0, [], res)

Example(Python)

Let us see the following implementation to get a better understanding −

class Solution(object):
   def permute(self, nums):
      result = []
      self.permute_util(nums,0,[],result)
      return result
   def permute_util(self,given_list,start,curr,result):
      if start > len(given_list)-1:
         #print(curr)
         result.append(curr)
         return
      for i in range(start,len(given_list)):
         self.swap(given_list,start,start+(i-start)) self.permute_util(given_list,start+1,curr+[given_list[start]],result)
         #print(given_list)
         self.swap(given_list, start, start + (i - start))
   def swap(self,nums,index1,index2):
      temp = nums[index1]
      nums[index1] = nums[index2]
      nums[index2] = temp
ob1 = Solution()
print(ob1.permute([1,2,3,4]))

Input

[1,2,3,4]

Output

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