虽然循环和元组
问题描述:
我想定义一个函数,它返回两个给定数字之间的所有整数的总和,但我在下面的最后一行代码中遇到了问题。例如,用户输入两个整数,例如(2,6),并且该函数将一起添加所有内容,2 + 3 + 4 + 5 + 6 = 20。我无法弄清楚如何使我的函数在输入(x)处开始并在输入(y)处结束。另外,我想使用while循环。虽然循环和元组
def gauss(x, y):
"""returns the sum of all the integers between, and including, the two given numbers
int, int -> int"""
x = int
y = int
counter = 1
while counter <= x:
return (x + counter: len(y))
答
您可以通过如下总和做到这一点:
In [2]: def sigma(start, end):
...: return sum(xrange(start, end + 1))
...:
In [3]: sigma(2, 6)
Out[3]: 20
如果你想使用while循环,你可以这样做:
In [4]: def sigma(start, end):
...: total = 0
...: while start <= end:
...: total += start
...: start += 1
...: return total
...:
In [5]: sigma(2, 6)
Out[5]: 20
答
def gauss(x, y):
"""returns the sum of all the integers between, and including, the two given numbers
int, int -> int"""
acc = 0 # accumulator
while x <= y:
acc += x
x += 1
return acc
除了:一更好的方法是不要使用sum
或range
或者根本不使用
def gauss(x, y):
return (y * (y + 1) - x * (x - 1)) // 2
+0
有趣! – 2015-02-09 04:48:27
我试着修复你的代码格式,但是'x = int'等没有意义 – 2015-02-09 04:34:34