我的代码非常慢。如何让它在 Python 中运行得更快? [已关闭]

问题描述 投票:0回答:1

这段代码给出了从1到31的6个数字的所有可能组合。但是它非常慢。运行需要几个小时。我的笔记本电脑在完成之前就耗尽了电池电量。如何让它运行得更快?

import math
from itertools import permutations
import itertools
import collections



perm = itertools.combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],6)
lst = []

for val in perm:

        lst.append(val)
        res = [list(ele) for ele in lst]
        size = len(res)
print(size)
print(res) 

python loops for-loop combinations
1个回答
0
投票

每次追加到

res
时,您都会计算
size
lst
,但仅打印最后一次迭代时的值。

特别是,

res
将迭代您已添加的每个项目,从而将其从 O(N) 操作变为 O(N²) 操作。

因此第一步是将这些操作移出循环。

您也可以使用推导式而不是循环,但是一旦您解决了大问题,这将只是几个百分点。

© www.soinside.com 2019 - 2024. All rights reserved.