簡體   English   中英

獲取范圍內所有數字的總和

[英]Get sum of all numbers in range

我的范圍是1到5。該范圍內的每個數字都會平方。

for x in range(1, 5 + 1):
  x = x ** 2
  print(x)

這樣做給我:1、4、9、16、25。

那是完美的,但是我該如何請求范圍內的新數字之和,以使其等於55?

累計總和:

>>> total = 0
>>> for x in range(1, 5+1):
...     total += x ** 2
...
>>> total
55

更優選地,使用sumgenerator表達式

>>> sum(x**2 for x in range(1, 5+1))
55

替代的方形金字塔數解 (由M4rtini建議):

(2*(5**3) + 3*(5**2) + 5)/6

或一般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

以上應該可以幫助您。 您想在將X計算成另一個變量時存儲和。 然后,您可以在程序中進一步使用總和。

一條線:

sum(x**2 for x in xrange(1,6))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM