Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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:
- #012 021 102 120 201 210
- #What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
- #Analysis
- #The following algorithm generates the next permutation lexicographically
- #after a given permutation. It changes the given permutation in-place.
- #1. Find the largest index k such that a[k] < a[k + 1]. If no such
- # index exists, the permutation is the last permutation.
- #2. Find the largest index l such that a[k] < a[l]. Since k + 1
- # is such an index, l is well defined and satisfies k < l.
- #3. Swap a[k] with a[l].
- #4. Reverse the sequence from a[k + 1] up to and including the final
- # element a[n].
- #Source: http://en.wikipedia.org/wiki/Permutation
- def perLexi(a):
- largestK = 0
- for k in range(len(a)-1):
- if a[k] < a[k+1] and k >= largestK :
- largestK = k
- if largestK == len(a) - 1:
- return a
- largestL = 0
- for l in range(len(a)):
- if a[largestK] < a[l] and l >= largestL :
- largestL = l
- a[largestK], a[largestL] = a[largestL], a[largestK]
- temp = a[largestK+1:]
- temp.reverse()
- for i in a[largestK+1:]:
- a.remove(i)
- for j in temp:
- a.append(j)
- return a
- s = [0,1,2,3,4,5,6,7,8,9]
- for i in range(999999):
- s = perLexi(s)
- print s
Advertisement
Add Comment
Please, Sign In to add comment