Given two integers, which can be positive and negative, find the sum of all the numbers between including them too and return it. If both numbers are equal return a or b.
def get_sum(a,b):
if a==b:
return a
else:
get_big = max([a,b])
get_small = min([a,b])
nums = xrange(get_small,get_big+1)
return sum(nums)
def get_sum1(a,b):
return sum(xrange(min(a,b), max(a,b)+1))
def get_sum2(a, b):
return (a + b) * (abs(a - b) + 1) // 2
range()
和 xrange()
用法相同,但range()
返回一个list,xrange()
返回一个xrange Object,是iterable的;xrange()
占用占用更少的内存空间,因为循环时xrange()
只生成当前的元素,不像 range()
一开始就生成list;range()
被移除了,xrange()
被重新命名为range()
;PS: CodeWars刚开始的题目都不是很难得