python - 任何加速 itertool.product 的方法

标签 python numpy nested-loops python-itertools

我正在使用 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/

相关文章:

java - 嵌套循环以查找计数

python - getChatMembersCount 远程机器人

python - 如何在 NLTK 中对二元语言模型进行单词级别的 Kneser-Ney 平滑?

python - 映射 - 特征重要性与标签分类

python - JAX:jit 函数的时间随着函数访问的内存而超线性增长

python - 插入数组时保留numpy掩码

python - 在 numpy 数组中将特定值设置为零

c# - 比使用 3 个嵌套 for 循环获取我需要的数据更好的方法

performance - matlab : vectorize 4D matrix sum

python - Lomb-Scargle 与 FFT 功率谱 : crashes with evenly spaced data