mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
Add Kth lexicographic permutation (#1179)
* Add Kth lexicographic permutation Function that computes the kth lexicographic permtation of 0,1,2,...,n-1 in O(n^2) time * Update kth_lexicographic_permutation.py Addressed requested changes
This commit is contained in:
parent
030600f9b3
commit
47d17951b8
40
maths/kth_lexicographic_permutation.py
Normal file
40
maths/kth_lexicographic_permutation.py
Normal file
@ -0,0 +1,40 @@
|
||||
def kthPermutation(k, n):
|
||||
"""
|
||||
Finds k'th lexicographic permutation (in increasing order) of
|
||||
0,1,2,...n-1 in O(n^2) time.
|
||||
|
||||
Examples:
|
||||
First permutation is always 0,1,2,...n
|
||||
>>> kthPermutation(0,5)
|
||||
[0, 1, 2, 3, 4]
|
||||
|
||||
The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],
|
||||
[0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],
|
||||
[1,2,3,0], [1,3,0,2]
|
||||
>>> kthPermutation(10,4)
|
||||
[1, 3, 0, 2]
|
||||
"""
|
||||
# Factorails from 1! to (n-1)!
|
||||
factorials = [1]
|
||||
for i in range(2, n):
|
||||
factorials.append(factorials[-1] * i)
|
||||
assert 0 <= k < factorials[-1] * n, "k out of bounds"
|
||||
|
||||
permutation = []
|
||||
elements = list(range(n))
|
||||
|
||||
# Find permutation
|
||||
while factorials:
|
||||
factorial = factorials.pop()
|
||||
number, k = divmod(k, factorial)
|
||||
permutation.append(elements[number])
|
||||
elements.remove(elements[number])
|
||||
permutation.append(elements[0])
|
||||
|
||||
return permutation
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
Loading…
Reference in New Issue
Block a user