Reputation: 127
Given a list of numbers, I would like to find all pairs of numbers that add up to 10.
How can I write a function to do this in Python?
Upvotes: 0
Views: 2085
Reputation: 13
This question is pretty old, but I thought I would contribute my own answer because both of the provided solutions at time of writing have subtle errors: one only provides one pair of numbers that adds up to 10; the other re-uses numbers (ex., even though 5 is only in the list once, (5, 5) gets listed as a solution in addition to repeating the pairs).
Using the itertools library, you can do the following:
from itertools import combinations
def pair_sums(arr, expected=10):
return [x for x in combinations(arr, 2) if sum(x) == expected]
arr1 = [2, 4, 5, 6, 8]
pair_sums(arr1) # returns [(2, 8), (4, 6)]
arr2 = [2, 5, 7, 5, 9, 3]
pair_sums(arr2) # returns [(5, 5), (7, 3)]
Upvotes: 0
Reputation: 93090
Just store the difference from 10 in a set:
def find(arr, total):
d = set()
for e in arr:
if e in d:
print total-e, e
break
d.add(total-e)
s = [1,5,3,10,11,7,2]
find(s, 10)
Upvotes: 5
Reputation: 235
l = [1, 3, 4, 5, 6, 7, 8, 9]
[(x,y) for x in l for y in l if x+y==10]
Upvotes: 3