首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >给出字典顺序中的元素列表(即['a','b','c','d']),找出第n次置换--平均求解时间?

给出字典顺序中的元素列表(即['a','b','c','d']),找出第n次置换--平均求解时间?
EN

Stack Overflow用户
提问于 2011-07-21 23:39:56
回答 3查看 2.1K关注 0票数 3

我偶然发现了这个面试问题:

给出字典顺序中的元素列表(即'a','b','c','d'),找到第n个置换

我自己试过了,我花了大约30分钟才解决。(我在Python中得到了一个~8-9行的解决方案)。只是好奇-需要多长时间才能解决这类问题?我是不是拖得太久了?

EN

回答 3

Stack Overflow用户

发布于 2011-07-22 00:15:38

9分钟,包括测试

代码语言:javascript
复制
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)
票数 11
EN

Stack Overflow用户

发布于 2017-09-09 16:11:09

当您查看“r-长度-置换”(由r参数itertools.permutations表示)时,如果有人对一个可以找到“I”置换的解决方案感兴趣:

代码语言:javascript
复制
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

例如:

代码语言:javascript
复制
>>> 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)

包括一个更完整的测试:

代码语言:javascript
复制
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)

这里使用了的部分答案。

票数 1
EN

Stack Overflow用户

发布于 2011-07-26 11:06:18

也许我错过了什么,我想我们可以通过迭代工具规则中的第n条排列轻松地找到它。

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6784148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档