25 XP

38. The missing number

Beginner math lists

A list should hold every whole number from 0 to n, once each, but one of them is missing, so the list has n items instead of n + 1. They can be in any order.

Write a function missing_number(numbers) that takes such a list and returns the number that is missing. It can be any of them: 0, n, or one in between. Since the list has n items, n is len(numbers).

You could look for each number in turn, but there is a quicker way: you know what the numbers from 0 to n add up to.

Example 1

Inputnumbers = [3, 0, 1]
Output2
Explanation3 items, so 0 to 3; 2 is the one missing.

Example 2

Inputnumbers = [0, 1]
Output2
Explanation2 items, so 0 to 2; the last is missing.

Example 3

Inputnumbers = [1]
Output0
Explanation1 item, so 0 and 1; 0 is the one missing.

Constraints

  • numbers has 1 to 50 items, in any order.
  • They are different whole numbers from 0 to len(numbers), with exactly one of those missing.

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

Practises Numbers and Math (lesson 3).

Code
def missing_number(numbers):
    """Find the number missing from 0 to len(numbers).

    numbers: list of int, every number from 0 to n but one,
        in any order (n is the list's length)
    Returns: int, the missing number
    """
    # Write your code here
    pass