0

Is there an easy way to compare 2 values in a dictionary to all other values? For example, if I have a dict:

dict = {A:12, B:1, C:14, D:13, E:3, F: 4}

I'd want to find all values that can be added together to equal another values. E.g. A + B = D, so A,B, and D would be returned.

4

3 回答 3

7

使用itertools.combinations

d = {'A':12, 'B':1, 'C':14, 'D':13, 'E':3, 'F': 4}

import itertools
for a, b, c in itertools.combinations(sorted(d, key=d.get), 3):
    if d[a] + d[b] == d[c]:
        print(a,b,c)

B E F
B A D
B D C

更新

如果您想要重复使用itertools.combinations_with_replacement

d = {'A':1, 'B':2, 'C':4}

import itertools
for a, b, c in itertools.combinations_with_replacement(sorted(d, key=d.get), 3):
    if d[a] + d[b] == d[c]:
        print(a,b,c)

A A B
B B C

为什么sorted使用?

比较x + y==z是没有意义的,如果xor yis 大于z。(假设所有值都是正整数)。我sorted以前是整理数据的; x <= y <= z.

排序的另一个副作用:如果A + B == C为真,B + A == C则也为真。但是使用sorted,只打印一个。


顺便说一句,不要dict用作变量名。它隐藏了内置dict函数。

于 2013-10-28T03:01:53.153 回答
2

这很容易,但效率不高(适用于小型听写)

>>> D = {'A':12, 'B':1, 'C':14, 'D':13, 'E':3, 'F': 4}
>>> 
>>> from itertools import product
>>> for i, j, k in product(D.items(), repeat=3):
...     if i[1] + j[1] == k[1]:
...         print "{} + {} = {}".format(i[0], j[0], k[0])
... 
A + B = D
B + A = D
B + E = F
B + D = C
E + B = F
D + B = C
于 2013-10-28T03:00:41.290 回答
2

这在非病理输入(例如全零)上以 O(n^2) 运行,而不是像这里的其他答案那样以 O(n^3) 运行,并正确处理重复项。

def addTriples(d):
    inverse = {v:[] for v in d.itervalues()}
    for k, v in d.iteritems():
        inverse[v].append(k)

    for k1, v1 in d.iteritems():
        for k2, v2 in d.iteritems():
            if k1 != k2:
                for k3 in inverse.get(v1 + v2, ()):
                    if k2 != k3:
                        yield (k1, k2, k3)

d = {'A':12, 'B':1, 'C':14, 'D':13, 'E':3, 'F':4}
for triple in addTriples(d):
    print triple

删除k1 != k2k2 != k3如果你想允许 A + A = B 和 A + B = A

于 2013-10-28T03:02:09.917 回答