1- def kth_permutation (k , n ) :
1+ def kth_permutation (k : int , n : int ) -> list [ int ] :
22 """
33 Finds k'th lexicographic permutation (in increasing order) of
44 0,1,2,...n-1 in O(n^2) time.
55
6+ :param k: The index of the permutation (0-based)
7+ :param n: The number of elements in the permutation
8+ :return: The k-th lexicographic permutation of size n
9+
610 Examples:
7- First permutation is always 0,1,2,...n
8- >>> kth_permutation(0,5)
11+ First permutation is always 0,1,2,...n-1
12+ >>> kth_permutation(0, 5)
913 [0, 1, 2, 3, 4]
1014
1115 The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],
1216 [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],
1317 [1,2,3,0], [1,3,0,2]
14- >>> kth_permutation(10,4)
18+ >>> kth_permutation(10, 4)
1519 [1, 3, 0, 2]
20+
21+ >>> kth_permutation(10, 0)
22+ Traceback (most recent call last):
23+ ...
24+ ValueError: n must be positive
25+
26+ >>> kth_permutation(-1, 5)
27+ Traceback (most recent call last):
28+ ...
29+ IndexError: k must be non-negative
30+
31+ >>> kth_permutation(120, 5)
32+ Traceback (most recent call last):
33+ ...
34+ IndexError: k out of bounds
1635 """
17- # Factorails from 1! to (n-1)!
36+ if n <= 0 :
37+ raise ValueError ("n must be positive" )
38+ if k < 0 :
39+ raise IndexError ("k must be non-negative" )
40+
41+ # Factorials from 1! to (n-1)!
1842 factorials = [1 ]
1943 for i in range (2 , n ):
2044 factorials .append (factorials [- 1 ] * i )
21- assert 0 <= k < factorials [- 1 ] * n , "k out of bounds"
45+
46+ if k >= factorials [- 1 ] * n :
47+ raise IndexError ("k out of bounds" )
2248
2349 permutation = []
2450 elements = list (range (n ))
@@ -28,7 +54,7 @@ def kth_permutation(k, n):
2854 factorial = factorials .pop ()
2955 number , k = divmod (k , factorial )
3056 permutation .append (elements [number ])
31- elements .remove (elements [number ])
57+ elements .pop ( number ) # elements. remove(elements[number]) is slower and redundant
3258 permutation .append (elements [0 ])
3359
3460 return permutation
0 commit comments