[英]Get sum of all numbers in range
I have a range from 1 to 5. Each number in that range gets squared. 我的范围是1到5。该范围内的每个数字都会平方。
for x in range(1, 5 + 1):
x = x ** 2
print(x)
Doing this, gives me: 1, 4, 9, 16, 25. 这样做给我:1、4、9、16、25。
That is perfect, but how do I then request the sum of the new numbers in the range so that they equal 55? 那是完美的,但是我该如何请求范围内的新数字之和,以使其等于55?
Accumulate the sum: 累计总和:
>>> total = 0
>>> for x in range(1, 5+1):
... total += x ** 2
...
>>> total
55
More preferably, using sum
and generator expression : 更优选地,使用sum
和generator表达式 :
>>> sum(x**2 for x in range(1, 5+1))
55
alternative square pyramidal number solution (as suggested by M4rtini): 替代的方形金字塔数解 (由M4rtini建议):
(2*(5**3) + 3*(5**2) + 5)/6
or for general n: 或一般n:
def square_pyramid(x):
return (2*(x**3) + 3*(x**2) + x)/6
total = 0
for x in range(1, 5 + 1):
x = x ** 2
total = total + x
print(x)
print total
The above should help you out. 以上应该可以帮助您。 You want to be storing the sum as you calculate X into another variable. 您想在将X计算成另一个变量时存储和。 You can then use the sum further along in your program. 然后,您可以在程序中进一步使用总和。
一条线:
sum(x**2 for x in xrange(1,6))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.