Reputation:
A few days back I encountered a problem which says that there is a list of numbers and a value called total. Now we need to write a program that gives a list of tuples (only 2 elements in the tuple) and sum of each tuple should be equal to the value of total. Example: Following is the input:
input = [1,2,3,4,6,7,8,9]
total = 10
Following is the output:
output = [(1,9), (2,8), (3,7), (4,6)]
Upvotes: 1
Views: 566
Reputation: 3787
You can find the difference and check if the value is a part of the remaining list as follows -
>>> [(index,i) for index,i in enumerate(input)] #how enumerate works
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 6), (5, 7), (6, 8), (7, 9)]
>>> [(i,total-i) for index,i in enumerate(input) if (total-i) in input[index+1:]]
[(1, 9), (2, 8), (3, 7), (4, 6)]
Upvotes: 0
Reputation: 14486
Using a list-comprehension with itertools.combinations
:
>>> import itertools
>>> inpt = [1,2,3,4,6,7,8,9]
>>> total = 10
>>> [p for p in itertools.combinations(inpt, 2) if sum(p) == total]
[(1, 9), (2, 8), (3, 7), (4, 6)]
Note you should not use input
as a variable name as it shadows the builtin input()
function.
To do this without itertools
, we can use the following list-comprehension:
>>> [(inpt[i],inpt[j]) for i in range(len(inpt)) for j in range(i+1, len(inpt)) if sum((inpt[i],inpt[j])) == total]
>>> [(1, 9), (2, 8), (3, 7), (4, 6)]
Upvotes: 3