Skip to content

Solving Number Zoo Patrol in Python

The challenge

Write a function that takes a shuffled list of unique numbers from 1 to n with one element missing (which can be any number including n). Return this missing number.

Note: huge lists will be tested.

Examples:

[1, 3, 4] => 2 [1, 2, 3] => 4 [4, 2, 3] => 1
Code language: plaintext (plaintext)

The solution in Python code

Option 1:

def find_missing_number(a): n = len(a) + 1 return n * (n + 1) // 2 - sum(a)
Code language: Python (python)

Option 2:

def find_missing_number(nums): return sum(range(1,len(nums)+2))-sum(nums)
Code language: Python (python)

Option 3:

def find_missing_number(numbers): if numbers == []:return 1 diff = list(set(range(1, len(numbers)+1))- set(numbers)) if diff == []:return max(numbers)+1 return diff[]
Code language: Python (python)

Test cases to validate our solution

test.assert_equals(find_missing_number([2, 3, 4]), 1) test.assert_equals(find_missing_number([1, 3, 4]), 2) test.assert_equals(find_missing_number([1, 2, 4]), 3) test.assert_equals(find_missing_number([1, 2, 3]), 4)
Code language: Python (python)

See also  How to create an Image Host Filename Generator in Python
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x