在列表中查找与给定值相加的值

时间:2015-05-08 18:52:18

标签: python algorithm python-2.7

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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:5)

查看var data = [], new_data = []; // Generate sample array of objects with index field for (var i = 500; i < 3700; i++) { data.push({ PKID: i, value: '1' }); } data.forEach(function(item) { new_data[item.PKID] = item; }); console.log(new_data); console.log(new_data.length); // 3700 but real length is 3200 other items are undefined

Select POTYPE, Count(POTYPE) From TableA Group By POTYPE

输出 -

itertools.combinations

答案 1 :(得分:2)

这是一种递归方法:

# 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)