简体   繁体   中英

How to find pair of numbers in a list which makes a sum as given number

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

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

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

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