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

我正在尝试编写简单和
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或无或类似的东西.

任何帮助将不胜感激.

最佳答案 这是一个递归方法:

# 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, t, A[i+1:], B)

        B.pop()        # drop [a] from possible list

A=[0.4, 2, 3, 1.4, 2.6, 6.3]
combination_in_range(5, 0.5, A)
点赞