如何计算定义为1 ^ 2 + 2 ^ 2 + 3 ^ 2 + ... + n2的平方和的值,直到达到用户指定的和

九条

这就是我所拥有的,但是我不知道如何设定范围,以便在达到总和时可以停止该范围。

total=0
x=0
n=int(input('What is the maximum sum? '))
while x in range():
    x=x+1
    y= x**2
    total= total+y
    print(total)
    if total>=n:
        print('Done')
阿巴内特

如果您不预先知道范围的界限,一种解决方案是只使用while True:,并break在达到目标时使用a

while True:
    x = x + 1
    y = x ** 2
    total = total + y
    if total >= n:
        break
print(total)

但是,如果您想变得聪明一点,可以从迭代器管道的角度来考虑。像这样:

numbers = itertools.count(1) # all positive integers
squares = (x**2 for x in numbers) # all squares of positive integers
totals = itertools.accumulate(squares) # all running totals of squares of ...
bigtotals = itertools.dropwhile(lambda total: total < n, totals) # all ... starting >= n
total = next(bigtotals) # first ... starting >= n

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章