HomeSoftware EngineeringFixing Quantity Zoo Patrol in Python

Fixing Quantity Zoo Patrol in Python


The problem

Write a perform that takes a shuffled checklist of distinctive numbers from 1 to n with one ingredient lacking (which might be any quantity together with n). Return this lacking quantity.

Word: large lists will probably be examined.

Examples:

[1, 3, 4]  =>  2
[1, 2, 3]  =>  4
[4, 2, 3]  =>  1

The answer in Python code

Choice 1:

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

Choice 2:

def find_missing_number(nums):
    return sum(vary(1,len(nums)+2))-sum(nums)

Choice 3:

def find_missing_number(numbers):
    if numbers == []:return 1
    diff = checklist(set(vary(1, len(numbers)+1))- set(numbers))
    if diff == []:return max(numbers)+1
    return diff[0]

Check circumstances to validate our answer

take a look at.assert_equals(find_missing_number([2, 3, 4]), 1)
take a look at.assert_equals(find_missing_number([1, 3, 4]), 2)
take a look at.assert_equals(find_missing_number([1, 2, 4]), 3)
take a look at.assert_equals(find_missing_number([1, 2, 3]), 4)
RELATED ARTICLES

Most Popular

Recent Comments