def sum_from_to(start, end):
"""Return the sum of the integers from start up to but not including end.
sum_from_to(int, int) -> int
"""
while
例子:
- sum_from_to(3, 7) 应计算为 18(即 3+4+5+6)。
- sum_from_to(3, 3) 应评估为 0。
我将如何处理这个?
def sum_from_to(start, end):
"""Return the sum of the integers from start up to but not including end.
sum_from_to(int, int) -> int
"""
while
我将如何处理这个?
只是为了好玩,您可以使用欧拉求和公式纯数学地解决这个问题:
def sum_from_to(start,stop):
return ((stop-1)*stop-(start-1)*start)/2
sum_from_to(3,7) #18
这具有计算成本非常低的好处。没有循环,没有范围,数组,你有什么。相比之下,其他功能很昂贵。
有更简单的解决方案。
sum(range(3, 7))
这将不包括最终值。所以你会得到你所需要的。
首先,如果这不是家庭作业问题,答案很简单:
def sum_from_to(start, end):
return sum(range(start, end))
在 Python 2.x 中,使用xrange
而不是range
. 就是这样。
如果这是一个家庭作业程序,并且您不允许使用sum
甚至range
是for
循环(此时我不得不想知道为什么他们甚至假装教您 Python,但无论如何......),这里有一个骨架:
def sum_from_to(start, end):
total = 0
value = start
while ???:
total = ???
value = ???
return total
需要填写“???” 部分。你如何value
不断计数,一次 1,直到它达到end
?你怎么做才能total
让它保持流动的总和?这就是它的全部。
作为进一步的提示:
您可以使用变量的旧值来生成新值。例如:
i = 1
i = i * 2 # now it's 2
i = i * 2 # now it's 4