python – 在list中查找与给定值相加的值

python – 在list中查找与给定值相加的值,第1张

概述我正在尝试编写简单和 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或无或类似的东西. 任何帮助将不胜感激. 这是 我正在尝试编写简单和 pythonic的代码来识别列表中值的组合,这些值在某个容差范围内总和到定义的值.

例如:

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

任何帮助将不胜感激.

解决方法 这是一个递归方法:

# V is the target value,t is the tolerance# A is the List of values# B is the subset of A that is still below V-tdef combination_in_range(V,t,A,B=[]):    for i,a in enumerate(A):        if a > V+t:    # B+[a] is too large            continue        # B+[a] can still be a possible List        B.append(a)        if a >= V-t:   # Found a set that works            print B        # recursively try with a reduced V        # and a shortened List A        combination_in_range(V-a,A[i+1:],B)        B.pop()        # drop [a] from possible ListA=[0.4,6.3]combination_in_range(5,0.5,A)
总结

以上是内存溢出为你收集整理的python – 在list中查找与给定值相加的值全部内容,希望文章能够帮你解决python – 在list中查找与给定值相加的值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1193369.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存