逐项平衡2组值

2024-09-19 23:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题似乎和其他人相似,但我还没有找到任何与我需要的东西相近的东西(我还在四处寻找以防万一)。我有一个项目(项目的细节是没有必要的),当我发现自己有一个负值和其他两个正值(浮点数)有限集的有限列表。以下面的示例集为例:

negative_values = [-0.246497, -0.341068]
positive_values_1 = [0.522148, 0.923764, 0.112573, 0.401668]
positive_values_2 = [0.281474]

这些集合的大小可以从空到N不等。我需要做的是获取第一个正集合中的值,并尝试(根据集合的不同可能不可能)通过将它们逐值相加,使负集合中的值为0

如果只有第一组不可能,则使用第二组,如果仍然不可能,则尽可能多地使用“负\u值”0中的值

对于上述集合,这将呈现如下内容:

def cancelOut(negative_values, positive_values_1, positive_values_2):
    # Algorith doing something

new_negative_values = [0, 0]
new_positive_values_1 = [0, 0.858347, 0.112573, 0.401668]
new_positive_values_2 = [0.281474]

所发生的情况是,正的值中的第一个值使负的值中的第一个值为0,并使第二个值接近0,然后正的值中的第二个值的一部分使负的值中的第二个值为0,然后算法完成。我只想把正数集中的值一个接一个地加到负数中的值,直到它们都是0或者直到正数集都是0

我不知道是否有一个简单的方法来做到这一点,或者我是否需要具体地遍历每一组值的值,并计算出我想要的

提前谢谢大家


Tags: 项目示例内容列表newdef细节values
1条回答
网友
1楼 · 发布于 2024-09-19 23:41:50

这里是一个开始-这将是一个逻辑和保持跟踪的事情演习

a = negative_values
b = positive_values_1
c = positive_values_2

ab的第一项开始

add the a and b item together  
   if the result is > 0 change a's item to 0  
      and get a's next item to use in the next iteration  
          use the result for the b item in the next iteration
   if the result is 0 change a and b's item to 0  
       and get the next items from a and b to use in the next iteration  
   if the result is < 0 change b's item to zero  
       and get b's next item for use in the next iteration
           use the result for the a item in the next iteration   
if you get a StopIteration for a you are done
    make the current item/index of b (or c) = the result
if you get a StopIteration for b, switch to c
if you get a StopIteration for c you are done
    make the current item/index of a = the result
repeat  

相关问题 更多 >