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
JavaScript
x
13
13
1
def get_sum(a,b):
2
res = 0
3
if b>a:
4
for i in range(a,b):
5
res = sum(range(a,b+1))
6
return res
7
if a > b:
8
for i in range (b,a):
9
res = sum(range(b,a+1))
10
return res
11
elif a == b:
12
return a
13
Advertisement
Answer
Maybe this?
JavaScript
1
8
1
def get_sum2(a, b):
2
if a == b:
3
return a
4
return sum([n for n in range(a, b+1)] if b > a else [n for n in range(b, a+1)])
5
6
if __name__=="__main__":
7
print(get_sum2(1, 3))
8