我正在使用 itertools.product 来查找 Assets 可以采用的可能权重,前提是所有权重之和总计为 100。
min_wt = 10
max_wt = 50
step = 10
nb_Assets = 5
weight_mat = []
for i in itertools.product(range(min_wt, (max_wt+1), step), repeat = nb_Assets):
if sum(i) == 100:
weight = [i]
if np.shape(weight_mat)[0] == 0:
weight_mat = weight
else:
weight_mat = np.concatenate((weight_mat, weight), axis = 0)
上面的代码可以工作,但是速度太慢,因为它会遍历 Not Acceptable 组合,例如 [50,50,50,50,50] 最终测试了 3125 个组合,而不是 121 个可能的组合。有什么方法可以在循环中添加“求和”条件来加快速度吗?
最佳答案
许多改进都是可能的。
对于初学者来说,可以使用 itertools.combinations_with_replacement() 来减少搜索空间,因为求和是可交换的。
此外,最后一个加数应该被计算而不是被测试。例如,如果 t[:4]
为 (10, 20, 30, 35)
,您可以将 t[4]
计算为 1 - sum(t)
,给出的值为 5。与在 (10, 20, 30, 35, x)
中尝试 100 个 x 值相比,这将提高 100 倍的速度。
关于python - 任何加速 itertool.product 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58823497/