Reputation: 3
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
Upvotes: 0
Views: 68
Reputation: 1158
Yup. Using the formula for the triangular numbers:
def get_sum(a,b):
if a > b:
b, a = a, b
sum_from_1_to_a = a * (a + 1) / 2
sum_from_1_to_b = b * (b + 1) / 2
return sum_from_1_to_b - sum_from_1_to_a
You can simplify this, obviously, but I left it this way so it is obvious how the formula is being applied.
Also, are you sure if a == b
you should return a
? Aren't there 0 numbers between them if they have the same value?
Upvotes: 0
Reputation: 73
One suggestion, when you find yourself trying to check for the order of parameters do something like this so you don't have to write the same code twice:
if a>b:
a,b = b,a
# your code
Upvotes: 0
Reputation: 101
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))
Upvotes: 0
Reputation: 389
a little math won't harm.
so this should work.
def get_sum(a,b):
return (b-a+1)*(a+b)/2
Upvotes: 3