Python,排列到排列索引函数

标签 python permutation python-itertools factorial

我有一个列表的一些排列:

>>> import itertools
>>> perms = list(itertools.permutations([0,1,2,3]))
>>> perms
[(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2), (0, 3, 2, 1), (1, 0, 2, 3), (1, 0, 3, 2), (1, 2, 0, 3), (1, 2, 3, 0), (1, 3, 0, 2), (1, 3, 2, 0), (2, 0, 1, 3), (2, 0, 3, 1), (2, 1, 0, 3), (2, 1, 3, 0), (2, 3, 0, 1), (2, 3, 1, 0), (3, 0, 1, 2), (3, 0, 2, 1), (3, 1, 0, 2), (3, 1, 2, 0), (3, 2, 0, 1), (3, 2, 1, 0)]
>>> len(perms)
24

我可以使用什么函数(无需访问列表 perm)来获取任意排列的索引,例如(0, 2, 3, 1) -> 3?

(您可以假设置换元素始终是整数的升序列表,从零开始。)

提示:可能涉及阶乘数系统。 https://en.wikipedia.org/wiki/Factorial_number_system

最佳答案

我突然想到了以下内容,但没有对其进行彻底测试。

from math import factorial
elements = list(range(4))
permutation = (3, 2, 1, 0)
index = 0
nf = factorial(len(elements))

for n in permutation:
    nf //= len(elements)
    index += elements.index(n) * nf
    elements.remove(n)

print(index)

编辑:nf/= len(elements) 替换为 nf//= len(elements)

关于Python,排列到排列索引函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61656230/

相关文章:

c++ - 所有排列 C++ 与 vector <int> 和回溯

python - 从我保存在本地文件系统上的配置单元查询输出中删除空行

python - 计算一下我还剩多少天才能活到 25,000 天,以及那个日期是哪一天

php - 无连续字母相同的排列数

java - 对应的排列数

python - 使用 itertools 进行枚举条件仅获取某些列表索引(python)

python - 将每个子列表项与每个其他子列表中的每个项进行匹配(python)

python - 使用 bokeh 或 matplotlib 绘制主题

python - 有没有一种Python式的方法从列表中获取两个元素(第一个,第二个)...(最后一个,第一个)

Python:获取投资组合的所有可能的权重组合