python算法:Beginner Series #3 Sum of Numbers


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

Note: a and b are not ordered!

Examples

get_sum(1, 0) == 1   // 1 + 0 = 1
get_sum(1, 2) == 3   // 1 + 2 = 3
get_sum(0, 1) == 1   // 0 + 1 = 1
get_sum(1, 1) == 1   // 1 Since both are same
get_sum(-1, 0) == -1 // -1 + 0 = -1
get_sum(-1, 2) == 2  // -1 + 0 + 1 + 2 = 2

初級解法:

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

大神解法:

def get_sum(a,b):
    return sum(xrange(min(a,b), max(a,b)+1))






發佈了36 篇原創文章 · 獲贊 5 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章