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