mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-24 05:21:09 +00:00
07e991d553
* ci(pre-commit): Add pep8-naming to `pre-commit` hooks (#7038) * refactor: Fix naming conventions (#7038) * Update arithmetic_analysis/lu_decomposition.py Co-authored-by: Christian Clauss <cclauss@me.com> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refactor(lu_decomposition): Replace `NDArray` with `ArrayLike` (#7038) * chore: Fix naming conventions in doctests (#7038) * fix: Temporarily disable project euler problem 104 (#7069) * chore: Fix naming conventions in doctests (#7038) Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
def kth_permutation(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
|
|
>>> kth_permutation(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]
|
|
>>> kth_permutation(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()
|