50 XP

50. Two sum

Intermediate dictionaries lists

Write a function two_sum(numbers, target) that takes a list of whole numbers and a whole number target, and returns the positions of the two numbers that add up to target, as a list [i, j] with i smaller than j.

  • Positions are indexes, counting from 0.
  • The two positions must be different: one item can't be used twice. Two equal numbers at different positions are fine, as in [5, 1, 5] with a target of 10.
  • Exactly one pair adds up to target in each list the tests give.

Checking every pair works, but takes about n * n / 2 steps. Can you do it in one pass through the list?

Example 1

Inputnumbers = [4, 9, 1, 6], target = 7
Output[2, 3]
Explanationnumbers[2] + numbers[3] is 1 + 6 = 7.

Example 2

Inputnumbers = [5, 1, 5], target = 10
Output[0, 2]
ExplanationTwo different 5s, at indexes 0 and 2.

Example 3

Inputnumbers = [1, 5, 9], target = 10
Output[0, 2]
Explanation5 + 5 would use the one 5 twice.

Constraints

  • numbers has 2 to 1000 whole numbers, each from -1000 to 1000.
  • target is a whole number from -2000 to 2000.
  • Exactly one pair of positions has numbers that add up to target.

Submit also runs 8 more tests you can't see.

Practises Dictionaries (lesson 11).

Code
def two_sum(numbers, target):
    """Find the two numbers that add up to target.

    numbers: list of int, with exactly one such pair
    target: int, the sum to look for
    Returns: list of two ints, [i, j], the pair's indexes,
        with i < j
    """
    # Write your code here
    pass