gpt4 book ai didi

python - 使用 for 循环求未知变量的平方

转载 作者:行者123 更新时间:2023-11-30 22:21:58 24 4
gpt4 key购买 nike

我试图弄清楚如何使用for循环找到未知变量的平方根。我得到的提示是:所以如果我们传入 3,你会输出0^2+1^2+2^2+3^2=14

这是我对脚本类(class)的介绍,我只是在竞争中不知所措。

最佳答案

一种方法是:

n = int(raw_input("Enter number")) # get the number, use input if you are using python 3.x
sum([i**2 for i in range(n+1)]) # form a list with squares and sum them

你也可以用 lambda 来做到这一点。就这样:

reduce(lambda x,y: x + y**2, range(n+1))

关于python - 使用 for 循环求未知变量的平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48479647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com