我偶然发现了这个面试问题:
给出字典顺序中的元素列表(即'a','b','c','d'),找到第n个置换
我自己试过了,我花了大约30分钟才解决。(我在Python中得到了一个~8-9行的解决方案)。只是好奇-需要多长时间才能解决这类问题?我是不是拖得太久了?
发布于 2011-07-22 00:15:38
9分钟,包括测试
import math
def nthperm(li, n):
n -= 1
s = len(li)
res = []
if math.factorial(s) <= n:
return None
for x in range(s-1,-1,-1):
f = math.factorial(x)
d = n / f
n -= d * f
res.append(li[d])
del(li[d])
return res
#now that's fast...
nthperm(range(40), 123456789012345678901234567890)发布于 2017-09-09 16:11:09
当您查看“r-长度-置换”(由r参数itertools.permutations表示)时,如果有人对一个可以找到“I”置换的解决方案感兴趣:
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)这里使用了的部分答案。
发布于 2011-07-26 11:06:18
也许我错过了什么,我想我们可以通过迭代工具规则中的第n条和排列轻松地找到它。
from itertools import permutations, islice
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
def main():
data = ['a', 'b', 'c', 'd']
n = 7 # 0 indexed
print nth(permutations(data), n)
if __name__ == "__main__":
main()https://stackoverflow.com/questions/6784148
复制相似问题