Ad
Code
Diff
  • from timeit import timeit
    from math import floor
    
    # 1. Can you implement another optimised function (sum_even_numbers2) using purely native python?
    #    Can you timeit to show it's faster and describe why it is.
    #    Can you also state if there are any pros or cons to how it is implemented?
    
    # 2. Can you implement another optimised function (sum_even_numbers3) using third party packages?
    #    Can you timeit to show it's faster and describe why it is.
    #    Can you also state if there are any pros or cons to how it is implemented?
    
    def sum_even_numbers1(numbers: list[int]) -> int:
        total = 0
        for num in numbers:
            if floor(num/2) == num/2:
                total += num
        return total
    
    # Floating point calculation is not required
    # Only one division required
    # float required 32byte, memory heavy
    def sum_even_numbers2(numbers: list[int]) -> int:
        total = 0
        for num in numbers:
            if num%2 == 0:
                total += num
        return total
    
    # needs to call that function from memory
    def sum_even_numbers3(numbers: list[int]) -> int:
        return sum(filter(lambda x: x > 0 and x%2 == 0, numbers))
    
    # generators are often faster
    def sum_even_numbers4(numbers: list[int]) -> int:
        return sum(num for num in numbers if not num%2)
        
    • from timeit import timeit
    • from math import floor
    • # 1. Can you implement another optimised function (sum_even_numbers2) using purely native python?
    • # Can you timeit to show it's faster and describe why it is.
    • # Can you also state if there are any pros or cons to how it is implemented?
    • # 2. Can you implement another optimised function (sum_even_numbers3) using third party packages?
    • # Can you timeit to show it's faster and describe why it is.
    • # Can you also state if there are any pros or cons to how it is implemented?
    • def sum_even_numbers1(numbers: list[int]) -> int:
    • total = 0
    • for num in numbers:
    • if floor(num/2) == num/2:
    • total += num
    • return total
    • # Floating point calculation is not required
    • # Only one division required
    • # float required 32byte, memory heavy
    • def sum_even_numbers2(numbers: list[int]) -> int:
    • total = 0
    • for num in numbers:
    • if num%2 == 0:
    • total += num
    • return total
    • # needs to call that function from memory
    • def sum_even_numbers3(numbers: list[int]) -> int:
    • return sum(filter(lambda x: x > 0 and x%2 == 0, numbers))
    • # generators are often faster
    • def sum_even_numbers4(numbers: list[int]) -> int:
    • return sum(num for num in numbers if not num%2)