princeofsudan

Project Euler#24 Lexicographic permutations

Mar 17th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. #A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, #2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. #The lexicographic permutations of 0, 1 and 2 are:
  2.  
  3. #012   021   102   120   201   210
  4.  
  5. #What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
  6.  
  7. #Analysis
  8. #The following algorithm generates the next permutation lexicographically
  9. #after a given permutation. It changes the given permutation in-place.
  10.  
  11. #1. Find the largest index k such that a[k] < a[k + 1]. If no such
  12. #   index exists, the permutation is the last permutation.
  13. #2. Find the largest index l such that a[k] < a[l]. Since k + 1
  14. #   is such an index, l is well defined and satisfies k < l.
  15. #3. Swap a[k] with a[l].
  16. #4. Reverse the sequence from a[k + 1] up to and including the final
  17. #   element a[n].
  18.  
  19. #Source: http://en.wikipedia.org/wiki/Permutation
  20.  
  21. def perLexi(a):
  22.     largestK = 0
  23.     for k in range(len(a)-1):
  24.         if a[k] < a[k+1] and k >= largestK :
  25.             largestK = k
  26.  
  27.     if largestK == len(a) - 1:
  28.         return a
  29.    
  30.     largestL = 0
  31.     for l in range(len(a)):
  32.         if a[largestK] < a[l] and l >= largestL :
  33.             largestL = l
  34.  
  35.     a[largestK], a[largestL] = a[largestL], a[largestK]
  36.     temp = a[largestK+1:]
  37.     temp.reverse()
  38.     for i in a[largestK+1:]:
  39.         a.remove(i)
  40.     for j in temp:
  41.         a.append(j)
  42.    
  43.     return a
  44.        
  45. s = [0,1,2,3,4,5,6,7,8,9]
  46.  
  47. for i in range(999999):
  48.     s = perLexi(s)
  49. print s
Advertisement
Add Comment
Please, Sign In to add comment