Advertisement
here2share

# permutate.py

May 10th, 2019
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. # permutate.py
  2.  
  3. def permutation(lst):
  4.  
  5.     # If lst is empty then there are no permutations
  6.     if len(lst) == 0:
  7.         return []
  8.  
  9.     # If there is only one element in lst then, only
  10.     # one permuatation is possible
  11.     if len(lst) == 1:
  12.         return [lst]
  13.  
  14.     # Find the permutations for lst if there are
  15.     # more than 1 characters
  16.  
  17.     l = [] # empty list that will store current permutation
  18.  
  19.     # Iterate the input(lst) and calculate the permutation
  20.     for i in range(len(lst)):
  21.        m = lst[i]
  22.  
  23.        # Extract lst[i] or m from the list.  remLst is
  24.        # remaining list
  25.        remLst = lst[:i] + lst[i+1:]
  26.  
  27.        # Generating all permutations where m is first
  28.        # element
  29.        for p in permutation(remLst):
  30.            l.append([m] + p)
  31.     return l
  32.  
  33.  
  34. # Driver program to test above function
  35. data = list('123')
  36. for p in permutation(data):
  37.     print p
  38.  
  39. '''
  40. Output:
  41.  
  42. ['1', '2', '3']
  43. ['1', '3', '2']
  44. ['2', '1', '3']
  45. ['2', '3', '1']
  46. ['3', '1', '2']
  47. ['3', '2', '1']
  48. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement