Advertisement
Guest User

Permutations in Python

a guest
Sep 21st, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. class Solution(object):
  2.     def permute(self, nums):
  3.         """
  4.        :type nums: List[int]
  5.        :rtype: List[List[int]]
  6.        """
  7.        
  8.         if (not nums):
  9.             return []
  10.  
  11.         N = len(nums)
  12.         if (N == 1):
  13.             return [nums]        
  14.  
  15.         A = nums    # rename
  16.  
  17.         # There should be N! permutations
  18.         def fac(n):
  19.             if (n < 0):
  20.                 return False
  21.             elif (n < 1):
  22.                 return 1
  23.             else:
  24.                 return n*fac(n-1)
  25.  
  26.             """
  27.            # Iterative:
  28.            
  29.            answer = 1
  30.            for i in xrange(1,n+1):
  31.                answer *= i
  32.  
  33.            return answer
  34.            """
  35.  
  36.         total = fac(N)
  37.         print("total perms: %i! = %i" % (N, total))
  38.  
  39.         # Generate all permutations
  40.         perms = []
  41.         for _ in xrange(total):
  42.             # Find pivot
  43.             pivot = None
  44.             for i in xrange(N-2, -1, -1):
  45.                 if (A[i] < A[i+1]):
  46.                     pivot = i
  47.                     break
  48.  
  49.             if pivot is None:
  50.                 A.reverse()
  51.                 copy = [n for n in A]           # Why is this necessary?
  52.                 perms.append(copy)
  53.             else:
  54.                 # Find successor in subarray
  55.                 successor = pivot+1         # Starting guess
  56.                 for j in xrange(pivot+1, N):
  57.                     if (A[j] > A[pivot] and
  58.                         (A[j] - A[pivot] <= A[successor] - A[pivot])):
  59.                             successor = j
  60.  
  61.                 # Swap pivot and successor
  62.                 A[pivot], A[successor] = A[successor], A[pivot]
  63.  
  64.                 # Reverse subarray
  65.                 A[pivot+1:] = reversed(A[pivot+1:])
  66.  
  67.                 # Add to list
  68.                 copy = [n for n in A]               # Why is this necessary?
  69.                 perms.append(copy)
  70.         return perms
  71.  
  72.  
  73. s = Solution()
  74.  
  75. # Test cases
  76. a0 = [1,2,3]
  77.  
  78. y0 = [
  79.   [1,2,3],
  80.   [1,3,2],
  81.   [2,1,3],
  82.   [2,3,1],
  83.   [3,1,2],
  84.   [3,2,1]]
  85.  
  86. print("input: %r" % a0)
  87. print("output: %r" % (s.permute(a0)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement