Skip to content
Advertisement

Trying to sum numbers between numbers more efficiently

TLDR: Need to make code below more efficient.

I’m trying to solve a coding challenge that requires I sum all numbers between two numbers. My code shown below is passing the tests but is taking too long to run, causing me to fail due to a time out.

Is there any way to rewrite this to do the same thing in less time?

EDIT: solved, thank you so much for your solutions

def get_sum(a,b):
    res = 0
    if b>a:
        for i in range(a,b):
            res = sum(range(a,b+1))
            return res
    if a > b: 
        for i in range (b,a):
            res = sum(range(b,a+1))
        return res
    elif a == b:
        return a

Advertisement

Answer

Maybe this?

def get_sum2(a, b):
    if a == b:
        return a
    return sum([n for n in range(a, b+1)] if b > a else [n for n in range(b, a+1)])

if __name__=="__main__":
    print(get_sum2(1, 3))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement