Python Practice › Function Programs › Program 21
Does any pair sum to 10?
Write a Python function that checks whether any two numbers in a list add up to 10.
Input
[2, 5, 6, 4, 7, 3, 8, 9, 1]
Output
True False
Approach
- Keep a set of numbers seen; for each number check whether
10 - nwas seen.
Solution
def has_pair(numbers, target=10): seen = set() for n in numbers: if target - n in seen: return True seen.add(n) return False print(has_pair([2, 5, 6, 4, 7, 3, 8, 9, 1]), has_pair([1, 2, 3]))Output
True False
Line by line
Line 4
If the partner value was already seen, a pair exists. This needs one pass instead of checking every pair.
Learn the concept
New to this topic? Read the lesson, then come back.