简体   繁体   中英

Python - recursive loop within a dict

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

eg twos

30  # 10 + 20
40  # 10 + 30
50  # 20 + 30

similarly for threes:

60 # 10 + 20 + 30

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]

You can use itertools.combinations to get all the combinations and then sum the results.

Eg

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

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

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 .

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM