python - 给定一个按字典顺序排列的元素列表(即 ['a' 、 'b' 、 'c' 、 'd' ]),找出第 n 个排列 - 求解的平均时间?

标签 python list recursion combinations

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

Given a list of elements in lexicographical order (i.e. ['a', 'b', 'c', 'd']), find the nth permutation

我自己试了一下,大约花了 30 分钟才解决。 (我最终得到了 ~8-9 行的 Python 解决方案)。只是好奇——“应该”解决这类问题需要多长时间?我是不是拖得太久了?

最佳答案

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)

关于python - 给定一个按字典顺序排列的元素列表(即 ['a' 、 'b' 、 'c' 、 'd' ]),找出第 n 个排列 - 求解的平均时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784148/

相关文章:

python - Django Rest Framework - 'module' 对象没有属性 'HStoreField'

python - 日期时间模块中异常消息的来源。值错误: year 10000 is out of range

python - 将列表转换为列表python中的随机列表

windows - Windows 中的 lshw 等价物是什么,它可以像 lshw 在 Linux 上那样给我一个硬件树结构?

java - 如何在main方法中从另一个类创建List对象?

python - 递归搜索

java - 程序似乎对于任何输入总是返回 1

python - python中字典的效率 :

python - 如何反转 CANTERA Python 模块中的 adiabetic.py 程序,使其输入绝热温度并给出输出入口温度?

python - 在 django 模板中渲染返回的字符串