Does any pair sum to 10?

EasyFunction Programs · 21 of 39

Write a Python function that checks whether any two numbers in a list add up to 10.

Advertisement
Input
[2, 5, 6, 4, 7, 3, 8, 9, 1]
Output
True False

Approach

  1. Keep a set of numbers seen; for each number check whether 10 - n was seen.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs