Skip to content

Commit d026807

Browse files
committed
Fix docstring and improve input validation in kth_lexicographic_permutation
1 parent 38c91df commit d026807

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

maths/kth_lexicographic_permutation.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
def 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
7+
First permutation is always 0,1,2,...,n-1
88
>>> kth_permutation(0,5)
99
[0, 1, 2, 3, 4]
1010
@@ -14,26 +14,36 @@ def kth_permutation(k, n):
1414
>>> kth_permutation(10,4)
1515
[1, 3, 0, 2]
1616
"""
17-
# Factorails from 1! to (n-1)!
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+
1824
factorials = [1]
1925
for i in range(2, n):
2026
factorials.append(factorials[-1] * i)
21-
assert 0 <= k < factorials[-1] * n, "k out of bounds"
27+
28+
max_k = factorials[-1] * n # equals n!
29+
if not (0 <= k < max_k):
30+
raise ValueError("k out of bounds")
2231

2332
permutation = []
2433
elements = list(range(n))
2534

2635
# Find permutation
2736
while factorials:
2837
factorial = factorials.pop()
29-
number, k = divmod(k, factorial)
30-
permutation.append(elements[number])
31-
elements.remove(elements[number])
32-
permutation.append(elements[0])
38+
index, k = divmod(k, factorial)
39+
permutation.append(elements[index])
40+
elements.pop(index)
3341

42+
permutation.append(elements[0])
3443
return permutation
3544

3645

46+
3747
if __name__ == "__main__":
3848
import doctest
3949

0 commit comments

Comments
 (0)