Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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? Thank you.

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading