Created
July 24, 2017 14:32
-
-
Save zopieux/90fc7565ff04af1e087d224fb66ba955 to your computer and use it in GitHub Desktop.
kth permutation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def kth_perm(n, k): | |
res = list(range(n)) | |
for i in range(n): | |
f = math.factorial(n - i - 1) | |
s, m = divmod(k, f) | |
if m == 0 and s == 0: | |
break | |
if s > 0: | |
for j in range(i - 1 + s, i - 1, -1): | |
res[j-1], res[j] = res[j], res[j-1] | |
if m == 0: | |
break | |
k = m | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment