Reputation: 657
Is there a cool way to traverse the dict recursively to get all the combination of the sum(values):
I have a dict {a: 10, b: 20, c:30}
I want to find all the unique combinations of twos and threes (Sum of the Values):
e.g. twos
30 # 10 + 20
40 # 10 + 30
50 # 20 + 30
similarly for threes:
60 # 10 + 20 + 30
Upvotes: 1
Views: 299
Reputation: 168646
For the example input you have given, you can use a combination of map
, sum
, and itertools.combinations
:
d = {'a': 10, 'b': 20, 'c':30}
import itertools
print map(sum, itertools.combinations(d.values(), 2))
print map(sum, itertools.combinations(d.values(), 3))
Or, in Python3:
d = {'a': 10, 'b': 20, 'c':30}
import itertools
print(list(map(sum, itertools.combinations(d.values(), 2))))
print(list(map(sum, itertools.combinations(d.values(), 3))))
prints:
[40, 30, 50]
[60]
Upvotes: 3
Reputation: 180441
Power set:
d={'a': 10, 'b': 20, 'c':30}
def power_set(items):
n = len(items)
for i in xrange(2**n):
combo = []
for j in xrange(n):
if (i >> j) % 2 == 1:
combo.append(items[j])
yield combo
data= [sum(x) for x in list(power_set(d.values())) if len(x)>1]
In [10]: data
Out[10]: [40, 30, 50, 60]
Upvotes: 0
Reputation: 11322
You can use itertools.combinations
to get all the combinations and then sum the results.
E.g.
from itertools import combinations
mydict = {'a': 10, 'b': 20, 'c':30}
twos = [sum(c) for c in combinations(mydict.values(), 2)]
threes = [sum(c) for c in combinations(mydict.values(), 3)]
print twos
print threes
Upvotes: 2
Reputation: 40894
Note: the solutions using combinations
above are better!
But I'll keep this anyway.
from itertools import permutations
data = {'a': 10, 'b': 20, 'c':30}
for key_perm in permutations(data.keys(), 2):
print ' + '.join(key_perm), '=', sum(data[k] for k in key_perm)
Prints:
a + c = 40
a + b = 30
c + a = 40
c + b = 50
b + a = 30
b + c = 50
But probably you want only distinct sums, since addition of integers is commutative. Sets come to the rescue.
for key_perm in set(tuple(sorted(perm)) for perm in permutations(data.keys(), 2)):
print ' + '.join(key_perm), '=', sum(data[k] for k in key_perm)
Prints:
b + c = 50
a + b = 30
a + c = 40
The use of tuple
above is needed because set()
only takes immutable items, and sorted()
returns a mutable list
.
Upvotes: 0
Reputation: 1953
You could use itertools
as follows:
import itertools
mydict = {'a': 10, 'b': 20, 'c':30}
result = [mydict[x] + mydict[y] for x, y in itertools.combinations(d, 2)]
Upvotes: 1