值的组合,基于列中对应的值

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

我有名为 Volume 的列,其中包含 [1.638, 0.625 , 5.001] 等值,总计值为 52000。

Part_Packing_Density 列包含 [0.73, 0.20, 0.3] 等值,总计值为 52000。

现在两根柱子的关系描述为 ,体积 1.638 的堆积密度为 0.73,体积 0.625 的堆积密度为 0.20,所有值均如此。

生成堆积密度值的所有可能组合,使相应体积值的总和约等于 40000。

例如,comb1 = [[0.73, 0.20, 0.3, 0.40],因此相应的音量值为 [1.638, 0.625 , 5.001, 44.621 ]。现在,如果我将这些音量值相加,例如 1.638+0.625+5.00+44.621...+...+.... 。应该是大约。 40000.

我尝试在单列中生成组合,但这不是最终目标。

我想要基于相应值相加的组合。就像我上面解释的那样。 帮助将不胜感激。

python-3.x list combinations python-itertools
1个回答
0
投票

您是否正在寻找类似的东西,或者也许我还没有完全理解。

import itertools

volume = [1.638, 0.625, 5.001, 44.621]  
packing_density = [0.73, 0.20, 0.3, 0.40]  
target_sum = 40000
tolerance = 100  # deviation

def combinations_with_sum(data, target_sum, tolerance):
    for i in range(1, len(data) + 1):
        for comb in itertools.combinations(data, i):
            volume_sum = sum(volume[j] for j in range(len(data)) if packing_density[j] in comb)
            if abs(volume_sum - target_sum) <= tolerance:
                yield comb

result = list(combinations_with_sum(packing_density, target_sum, tolerance))
print(result)  
© www.soinside.com 2019 - 2024. All rights reserved.