【问题标题】:Balance 2 sets of values item by item逐项平衡2组数值
【发布时间】:2019-01-11 19:25:16
【问题描述】:

我的问题可能看起来与其他问题相似,但我还没有找到任何与我需要的东西相近的东西(我仍在四处寻找以防万一)。当我发现自己有一个有限的负值列表和另外两个有限的正值集(浮点数)时,我有一个项目(不需要项目的详细信息)。以下面的示例集为例:

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

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

如果只使用第一个不可行,则使用第二组,如果仍然不可行,则尽可能多地将 'negative_values' 中的值设为 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]

发生的事情是positive_values_1中的第一个值使negative_value中的第一个值为0,并将第二个值增加到接近0。然后positive_values_1中的第二个值的一部分使negative_value中的第二个值为0,然后算法完成.我只是想将positive集合中的值与negative_value中的值一一添加,直到它们都为0或直到positive_value集合都为0。

我不知道是否有一种简单的方法可以做到这一点,或者我是否需要专门逐个遍历每个设置值并计算我想要的。

提前谢谢大家!

【问题讨论】:

  • canceled out 是什么意思?您是否正在寻找大小相等但符号相反的项目?如果您尝试过某些东西,您应该将其添加到您的问题中并告诉我们为什么它不起作用。 - minimal reproducible example - 您的示例数据应该允许我们测试任何解决方案
  • 我们应该能够复制和粘贴您的示例并使用它们来测试解决方案。那些... 无济于事 - 你越容易得到的答案就越多。
  • 不一定相等,但符号相反。我没有尝试过任何代码方面的事情,我想做的就是将积极的一面逐一添加到消极的一面,但我想知道是否有一种有效的方法。给出的数据足以做我想做的事:)
  • 如果值的大小不相等,则不清楚在这种情况下 cancel out 意味着什么。 DV 直到澄清。
  • 成为...absolute lover of programming... 你最好的选择是尝试一些事情,任何事情并尝试让它发挥作用。一旦你得到它的工作,那么你可以担心效率/优化 - 很多时候它会足够好。如果您在尝试使其工作时遇到困难 - 请在此处提出更具体的问题。如果文本描述不准确,发布您的代码还可以帮助我们弄清楚您要做什么。

标签: python list project balance


【解决方案1】:

这是一个开始的地方 - 这将是一个逻辑和跟踪事物的练习。

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  

【讨论】:

  • 谢谢!这似乎(至少在文本方面)就像我正在尝试做的事情。我会尽快尝试并确认它是否有效:D
  • 我试图投赞成票,但 dawg 投反对票意味着我不能,对不起。
  • np,我把它做成了一个 wiki,所以无论如何我都没有得到投票:)
猜你喜欢
  • 1970-01-01
  • 2020-10-09
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
相关资源
最近更新 更多