加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:42:48 所属栏目:Python 来源:网络整理
导读:我正在尝试编写简单和 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)等.如果没有找到任何组合,那么该函数应返回
我正在尝试编写简单和 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-t
def 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 list

A=[0.4,6.3]
combination_in_range(5,0.5,A)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读