gpt4 book ai didi

python - 在列表中查找总和为给定值的值

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:05:29 25 4
gpt4 key购买 nike

我正在尝试编写一些简单的 pythonic 代码来识别列表中的值组合,这些值的总和为定义的值,在一定的公差范围内。

例如:

如果 A=[0.4,2,3,1.4,2.6,6.3] 并且目标值为 5 +/- 0.5,那么我想要的输出是(2,3), (1.4,2.6), (2,2.6), (0.4,2,3), (0.4,3,1.4) 等如果没有找到组合则函数应该返回 0 或无或类似的东西。

如有任何帮助,我们将不胜感激。

最佳答案

看看 itertools.combinations

def first_attempt(A=A):
for i in xrange(1,len(A)+1):
print [comb
for comb in list(itertools.combinations(A,i))
if 4.5 < sum(map(float, comb)) < 5.5
]
## -- End pasted text --

In [1861]: %timeit first_attempt
10000000 loops, best of 3: 29.4 ns per loop

输出-

In [1890]: first_attempt(A=A)
[]
[(2, 3), (2, 2.6)]
[(0.4, 2, 3), (0.4, 2, 2.6), (0.4, 3, 1.4)]
[]
[]
[]

关于python - 在列表中查找总和为给定值的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30130890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com