以防万一有人对当您查看“r-length-permutations”时可以找到“第 i 个”排列的解决方案感兴趣(由 itertools.permutations 的 r 参数表示):
from math import factorial
def ith_permutation(i, seq, r=None):
li = list(seq)
length = len(li)
if r is None:
r = length
res = []
current_factorial = factorial(length) // factorial(length - r)
if current_factorial <= i:
raise ValueError('out of range')
for x in range(length, length-r, -1):
current_factorial //= x
div, mod = divmod(i, current_factorial)
i = mod
res.append(li[div])
del(li[div])
return res
例如:
>>> ith_permutationutation(10, [0, 1, 2, 3, 4], 2)
[2, 3]
>>> # correctness check:
>>> from itertools import permutations
>>> list(permutations([0, 1, 2, 3, 4], 2))[10]
(2, 3)
包括更完整的测试:
s = range(8)
for n in range(len(s)):
for idx, item in enumerate(permutations(s, n)):
assert list(item) == ith_permutation(idx, s, n)
这里使用了 Karoly Horvath 的部分答案。