小编典典

在Python中生成唯一排列

python

我正在寻找列表的唯一排列,x = [“ $ 5”,“ $ 10”,“ $ 10”,“ TAX”,“ $ 5”,“ 20%”,“ BOGO”,“
BOGO”,“ TAX “](9人一组)

我目前正在做的是

from itertools import permutations
x = ["$5", "$10", "$10", "TAX", "$5", "20%", "BOGO", "BOGO", "TAX"]
combos = []
for i in permutations(x, 9):
    if i not in combos:
        combos.append(i)
print combos

但是,这需要很长时间才能运行,我想知道是否有人可以为我提供更有效的解决方案。


阅读 276

收藏
2021-01-20

共1个答案

小编典典

if i not in combos:这将花费很长时间,因为列表中的成员资格测试是(最坏的情况)O(N)-它必须扫描每个元素。您可以set改用:

>>> from itertools import permutations
>>> x = ["$5", "$10", "$10", "TAX", "$5", "20%", "BOGO", "BOGO", "TAX", "BOGO"]
>>> %time p = set(permutations(x, 9))
CPU times: user 0.88 s, sys: 0.01 s, total: 0.90 s
Wall time: 0.90 s
>>> len(p)
75600
2021-01-20