You need to sign in or sign up before continuing.×
Ad
Code
Diff
  • def slow_sum(lst):
        
        sum = 0
        
        for num in lst:
            sum += num
        
        return sum
    
    • def slow_sum(lst):
    • if not lst:
    • return 0
    • lst = sorted(lst, key=lambda x: str(x))
    • sum = 0
    • lst = [int(str(num)) for num in lst]
    • def recursive_addition(l):
    • if len(l) == 1:
    • return l[0]
    • return l[0] + recursive_addition(l[1:])
    • total = 0
    • for num in lst:
    • total += recursive_addition([num])
    • return total
    • sum += num
    • return sum

You've been cursed with the most inefficient sum function ever created.

It's so bad that every time you run it, a computer science professor somewhere cries.

Your task: Fix it.

Your function should take a list of numbers and return their sum. But instead of taking minutes to run, it should be as efficient as possible (seriously, this thing is embarrassing).

Your Challenge:
Optimize this atrocious code. Make it run fast. Make it not terrible. Save humanity.

def slow_sum(lst):
    if not lst:  
        return 0  
    
    lst = sorted(lst, key=lambda x: str(x))  

    
    lst = [int(str(num)) for num in lst]

    
    def recursive_addition(l):
        if len(l) == 1:
            return l[0] 
        return l[0] + recursive_addition(l[1:])
    
    
    total = 0
    for num in lst:
        total += recursive_addition([num])  

    return total