繁体   English   中英

如何在 python 中更快地进行组合

[英]How to make combinations faster in python

我正在 python 中编写代码,其中我需要最多 1000 个元素的所有可能组合,然后对它们执行多个操作。 有什么办法可以减少运行时间。 通过使用 itertools,运行时间只需 50 个元素后的几分钟。 目前我正在使用这段代码(我已经注释掉了 print 语句,因为它显着增加了运行时间):

import itertools
import time

def all_combos_func(arguments):
    data = list(arguments)
    return itertools.chain.from_iterable(itertools.combinations(data, r) for r in range(len(data)+1))

start_time = time.time()

all_comb= []
for i in range (1000):
    all_comb.append(i+1)
all_combos = all_combos_func(all_comb)
all_combos_count = []
for i in all_combos:
    all_combos_count.append(i)
    # print(i)
print("this is the total length", len(all_combos_count))
end_time = time.time()

print(end_time-start_time)
>>> len(all_combos_func(range(0))
1
>>> len(all_combos_func(range(1))
2
>>> len(all_combos_func(range(2))
4
>>> len(all_combos_func(range(3))
8
>>> len(all_combos_func(range(4))
16

您的all_combos_func正在返回2^(len(input))组合。 因此,当您要求所有组合并传入 1000 个元素列表时,您会得到 2^1000 个结果。 是的,这需要一段时间。

2^1000 = 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM