1. 問題描述
2. 代碼
3. 總結(jié)
一、問題描述:
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.
二、代碼:
1. My Solution
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)
2. Other Solutions
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
三洽故、總結(jié)
- 在python2中饰躲,
range()
和xrange()
用法相同,但range()
返回一個(gè)list,xrange()
返回一個(gè)xrange Object烹看,是iterable的昔驱; -
xrange()
占用占用更少的內(nèi)存空間疹尾,因?yàn)檠h(huán)時(shí)xrange()
只生成當(dāng)前的元素,不像range()
一開始就生成list骤肛; - 在python3中纳本,
range()
被移除了,xrange()
被重新命名為range()
腋颠;
PS: CodeWars剛開始的題目都不是很難的