This question in the code challenge site really makes my head spinning, here is the question:

Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including themselves and return the total. If the two numbers are equal return a or b.

Note: a and b are not ordered!

As you can see the question above is really tricky and here is the answer to the above question:

def sum(a, b): agreat = False # is a greater than b? numberlist = [a, b] diff = 0 # this is for the loop control if(a > b): diff = a -b agreat = True elif(b > a): diff = b - a agreat = False else: return a i = 1 sum = 0 nextnumber = 0 firstloop = False # we need to check whether is it first time looping or not while(i < diff): if(agreat == True): if(firstloop == False): numberlist.append(b+1) nextnumber = b + 1 firstloop = True else: numberlist.append(nextnumber+1) nextnumber += 1 elif(agreat == False): if(firstloop == False): numberlist.append(a+1) nextnumber = a + 1 firstloop = True else: numberlist.append(nextnumber+1) nextnumber += 1 i += 1 for number in numberlist: sum += number # finally sum up all those numbers return sum

This one is done in a quick manner therefore there are still possible to further shorthorn the solution. Go ahead and enter your own code in the comment box below. :0

## Leave a Reply

5 Comments on "Find the sum of all the numbers between two integer including themselves"

This can be done mathematically without any loops:

def sum_between_inclusive(a,b):

if(a == b):

return a

if(a > b):

tmp = a

a = b

b = tmp

if(a == 1):

return (b * (b+1)) / 2

return ((b * (b+1))/2) – (((a-1)*((a-1)+1))/2)

source: https://www.wikihow.com/Sum-the-Integers-from-1-to-N

I don’t understand how you came with a code that bad…

The problem is extremely trivial:

“`

def sum(a, b):

if a > b:

a, b = b, a

if a == b:

return a

total = 0

while a <= b:

total += a

a += 1

return total

“`

def sumto(x):

return round(x/2*(x+1))

def sum(a, b):

if(a > b):

return (sumto(a) – sumto(b-1))

else:

return (sumto(b) – sumto(a-1))

{{{

def sumto(x):

return round(x/2*(x+1))

def sum(a, b):

if(a > b):

return (sumto(a) – sumto(b-1))

else:

return (sumto(b) – sumto(a-1))

}}}