11def kth_permutation (k , n ):
22 """
33 Finds k'th lexicographic permutation (in increasing order) of
4- 0,1,2,..., n-1 in O(n^2) time.
4+ 0,1,2,...n-1 in O(n^2) time.
55
66 Examples:
7- First permutation is always 0,1,2,...,n-1
7+ First permutation is always 0,1,2,...n
88 >>> kth_permutation(0,5)
99 [0, 1, 2, 3, 4]
1010
@@ -14,32 +14,23 @@ def kth_permutation(k, n):
1414 >>> kth_permutation(10,4)
1515 [1, 3, 0, 2]
1616 """
17- # Factorials from 1! to (n-1)!
18- if not isinstance (k , int ) or not isinstance (n , int ):
19- raise TypeError ("k and n must be integers" )
20-
21- if n < 1 :
22- raise ValueError ("n must be a positive integer" )
23-
17+ # Factorails from 1! to (n-1)!
2418 factorials = [1 ]
2519 for i in range (2 , n ):
2620 factorials .append (factorials [- 1 ] * i )
27-
28- max_k = factorials [- 1 ] * n # equals n!
29- if not (0 <= k < max_k ):
30- raise ValueError ("k out of bounds" )
21+ assert 0 <= k < factorials [- 1 ] * n , "k out of bounds"
3122
3223 permutation = []
3324 elements = list (range (n ))
3425
3526 # Find permutation
3627 while factorials :
3728 factorial = factorials .pop ()
38- index , k = divmod (k , factorial )
39- permutation .append (elements [index ])
40- elements .pop (index )
41-
29+ number , k = divmod (k , factorial )
30+ permutation .append (elements [number ])
31+ elements .remove (elements [number ])
4232 permutation .append (elements [0 ])
33+
4334 return permutation
4435
4536
0 commit comments