我希望找到列表的独特排列,x = ["$ 5","$ 10","$ 10","TAX","$ 5","20%","BOGO","BOGO","税" "]以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
Run Code Online (Sandbox Code Playgroud)
然而,这需要太长时间才能运行,我想知道是否有人能给我一个更有效的解决方案.
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3891 次 |
| 最近记录: |