擅长:python、mysql、java
<p>这并不难:</p>
<pre><code>def nthperm(l, n):
l = list(l)
indices = []
for i in xrange(1, 1+len(l)):
indices.append(n % i)
n //= i
indices.reverse()
perm = []
for index in indices:
# Using pop is kind of inefficient. We could probably avoid it.
perm.append(l.pop(index))
return tuple(perm)
</code></pre>
<p>这里的想法是,列表<code>l</code>的第<code>n</code>排列从第<code>n // factorial(len(l) - 1)</code>项开始,并继续<code>l</code>的其余元素的第{<cd4>}排列。在</p>
<p>如果你测试它,你会发现它确实有效:</p>
^{pr2}$
<p>对于迭代<code>itertools.permutations</code>永远无法完成的输入,它的工作速度足够快:</p>
<pre><code>>>> nthperm(range(100), factorial(100) // 2)
(50, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2
1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 4
1, 42, 43, 44, 45, 46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 6
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 8
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99)
</code></pre>