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:
JavaScript
x
2
1
(Mike, Kate) 7
2
I’ve tried below. The result comes out, but not the names of pairs:
JavaScript
1
16
16
1
import itertools
2
3
Mike = 3
4
Kate = 4
5
Leo = 5
6
David = 5
7
8
data = [Mike, Kate, Leo, David]
9
10
for L in range(0, len(data)+1, 2):
11
for subset in itertools.combinations(data, L):
12
if len(subset) == 2:
13
print (subset,sum(subset)) ---- (3, 4) 7
14
# print (''.join(subset),sum(subset)) ---- doesn't work
15
16
What’s the right way to do it?
Advertisement
Answer
If you use a dict instead of named variables, you can easily convert the names themselves into the int values via dictionary lookups.
JavaScript
1
12
12
1
import itertools
2
3
data = {
4
'Mike': 3,
5
'Kate': 4,
6
'Leo': 5,
7
'David': 5,
8
}
9
10
for subset in itertools.combinations(data, 2):
11
print(subset, sum(data[name] for name in subset))
12
JavaScript
1
7
1
('Mike', 'Kate') 7
2
('Mike', 'Leo') 8
3
('Mike', 'David') 8
4
('Kate', 'Leo') 9
5
('Kate', 'David') 9
6
('Leo', 'David') 10
7