gpt4 book ai didi

python - 计算列表中数字平方和的函数

转载 作者:行者123 更新时间:2023-11-28 20:03:29 25 4
gpt4 key购买 nike

我正在尝试编写一个函数 sum_of_squares(xs) 来计算列表 xs 中数字的平方和。例如,sum_of_squares([2, 3, 4]) 应该返回 4+9+16 即 29:

这是我尝试过的:

import random

xs = []

#create three random numbers between 0 and 50

for i in range(3):
xs.append(random.randint(0,50))

def sum_of_squares(xs):

#square the numbers in the list

squared = i ** i

#add together the squared numbers

sum_of_squares = squared + squared + squared

return sum_of_squares

print (sum_of_squares(xs))

现在这总是打印

12

因为它将 i 作为列表中整数的数量而不是整数的值。对于列表中的尽可能多的整数,我如何说“将值乘以整数的值”以获得平方值?

问这个问题让我尝试了这个:

import random

xs = []

#create three random numbers between 0 and 50

for i in range(3):
xs.append(random.randint(0,50))

def sum_of_squares(xs):

#square the numbers in the list

for i in (xs):
squared = i ** i

#add together the squared numbers

sum_of_squares = squared + squared + squared

return sum_of_squares

print (sum_of_squares(xs))

但它似乎没有正确地计算整数值的平方 - 我不确定它在做什么。看这个截图See ScreenshotVisualize Python演练。

最佳答案

def sum_of_squares(xs):
return sum(x * x for x in xs)

关于python - 计算列表中数字平方和的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40918917/

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