python - 在不评估完整迭代器的情况下获取特定排列 (itertools.permutation)

标签 python algorithm python-itertools

<分区>

我想访问几个固定样本来排列长列表。显然我可以做到:

In [18]: import itertools

In [19]: l = [p for p in itertools.permutations(range(10))]

In [20]: len(l)
Out[20]: 3628800

In [21]: l[256766]
Out[21]: (0, 7, 3, 9, 5, 6, 4, 2, 1, 8)

但这会导致长列表 l 被评估以创建列表。对于 10 项列表仍然是可能的。挂起较大的列表。

有没有办法在不创建完整列表的情况下通过调用其编号来获得特定排列?

请注意,我不想访问随机播放。我希望它是相同的排列,最好是“排列数”与使用 itertools.permutations 时调用的列表位置匹配。

编辑:回复:重复。也欢迎与 itertools 模块相关的答案(参见下面的讨论)。因此虽然目标与 Ranking and unranking of permutations with duplicates 中的目标相同在 itertools 上下文中的讨论可能仍然是值得的。

最佳答案

并不难:

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)

这里的想法是列表 l 的第 n 排列从项目 n//factorial(len(l) - 1) 并继续 n % factorial(len(l) - 1) l 剩余元素的第 permutation。

如果你测试它,你会发现它确实有效:

>>> all(perm == nthperm(range(5), i) for i, perm in enumerate(itertools.permutations(range(5))))
True

而且对于迭代 itertools.permutations 永远不会完成的输入,它的工作速度足够快:

>>> 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)

关于python - 在不评估完整迭代器的情况下获取特定排列 (itertools.permutation),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166621/

相关文章:

python - 在 Django 的 DetailView 中使用 get_object() 和aggregate()

python - 保持用户跨站点登录

c++ - 为具有 1 和 2 字节字符的字符集实现退格

python - 更改 `itertools.product`迭代顺序

Python 类型转换/转换语法差异

python - ValueError : Shapes (None, 1) 和 (None, 2) 不兼容(使用 keras 和 opencv 的卷积神经网络)

algorithm - worker 调度算法

javascript - 计算圆度

Python:使用itertools从文本文件中获取列表中的上一个、当前和下一个项目

python - itertools.groupby() 有什么用?