1- def kth_permutation (k : int , n : int ) -> list [ int ] :
1+ def kth_permutation (k , n ) :
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-
106 Examples:
11- First permutation is always 0,1,2,...n-1
12- >>> kth_permutation(0, 5)
7+ First permutation is always 0,1,2,...n
8+ >>> kth_permutation(0,5)
139 [0, 1, 2, 3, 4]
1410
1511 The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],
1612 [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],
1713 [1,2,3,0], [1,3,0,2]
18- >>> kth_permutation(10, 4)
14+ >>> kth_permutation(10,4)
1915 [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
3516 """
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)!
17+ # Factorails from 1! to (n-1)!
4218 factorials = [1 ]
4319 for i in range (2 , n ):
4420 factorials .append (factorials [- 1 ] * i )
45-
46- if k >= factorials [- 1 ] * n :
47- raise IndexError ("k out of bounds" )
21+ assert 0 <= k < factorials [- 1 ] * n , "k out of bounds"
4822
4923 permutation = []
5024 elements = list (range (n ))
@@ -54,9 +28,7 @@ def kth_permutation(k: int, n: int) -> list[int]:
5428 factorial = factorials .pop ()
5529 number , k = divmod (k , factorial )
5630 permutation .append (elements [number ])
57- elements .pop (
58- number
59- ) # elements.remove(elements[number]) is slower and redundant
31+ elements .remove (elements [number ])
6032 permutation .append (elements [0 ])
6133
6234 return permutation
0 commit comments