38. The missing number
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
numbers = [3, 0, 1]2Example 2
numbers = [0, 1]2Example 3
numbers = [1]0Constraints
numbershas 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).
- With nothing missing, the list would be 0, 1, 2, ..., n, where
n = len(numbers). What do those add up to? - 0 + 1 + ... + n is
n * (n + 1) // 2: for n = 3 that's 6, which is 0 + 1 + 2 + 3. - Take
sum(numbers)away from that total: what is left is the missing number. It works when 0 or n is the one missing, and the order doesn't matter.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.