python - 逐项平衡2组数值
问题描述
我的问题可能看起来与其他人相似,但我还没有找到任何接近我需要的东西(我仍在四处寻找以防万一)。当我发现自己有一个有限的负值列表和另外两个有限的正值集(浮点数)时,我有一个项目(不需要项目的详细信息)。以下面的示例集为例:
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,然后算法完成。我只是想将正集合中的值与negative_value中的值一一相加,直到它们都为0或直到positive_value集合都为0。
我不知道是否有一种简单的方法可以做到这一点,或者我是否需要专门逐个遍历每个设置值并计算我想要的。
提前谢谢大家!
解决方案
这是一个开始的地方 - 这将是一个逻辑和跟踪事物的练习。
a = negative_values
b = positive_values_1
c = positive_values_2
从 和 的第一项a
开始b
。
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
推荐阅读
- reactjs - FirebaseError: Function CollectionReference.add() 要求它的第一个参数是对象类型,但它是:一个函数
- php - 如何使用 jcrop 裁剪正确的图像
- r - R,列出学生为“B”或“C”的科目
- java - JUnit:放置测试方法的最佳策略
- r - 如何使用 R 将一个脚本中的变量调用到另一个脚本中?
- lua - 如何从字符串中提取数字?
- node.js - Sequilize PostgreSQL 查询,其中数组包含整数
- javascript - 用 forEach 重写 for 循环
- javascript - 动态添加到不同的 JS 对象数据 - 在循环或开关等?
- .net - 5秒查看部署状态