Search code examples
pythonloopstuplescombinations

Output variable names when summing a tuple


A list of variables with assigned values. I want to return all the possible combinations from each pair (every two of them).

The print-out is the names of the pair, and sum of them.

For example:

(Mike, Kate) 7

I've tried below. The result comes out, but not the names of pairs:

import itertools
    
Mike = 3
Kate = 4
Leo = 5
David = 5

data = [Mike, Kate, Leo, David]

for L in range(0, len(data)+1, 2):
    for subset in itertools.combinations(data, L):
        if len(subset) == 2:
            print (subset,sum(subset))              ---- (3, 4) 7
            # print (''.join(subset),sum(subset))   ---- doesn't work
        

What's the right way to do it?


Solution

  • If you use a dict instead of named variables, you can easily convert the names themselves into the int values via dictionary lookups.

    import itertools
        
    data = {
        'Mike': 3,
        'Kate': 4,
        'Leo': 5,
        'David': 5,
    }
    
    for subset in itertools.combinations(data, 2):
        print(subset, sum(data[name] for name in subset))
    
    ('Mike', 'Kate') 7
    ('Mike', 'Leo') 8
    ('Mike', 'David') 8
    ('Kate', 'Leo') 9
    ('Kate', 'David') 9
    ('Leo', 'David') 10