Skip to content

Instantly share code, notes, and snippets.

@zopieux
Created July 24, 2017 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zopieux/90fc7565ff04af1e087d224fb66ba955 to your computer and use it in GitHub Desktop.
Save zopieux/90fc7565ff04af1e087d224fb66ba955 to your computer and use it in GitHub Desktop.
kth permutation
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