python如下函数返回两个数的平方和_计算Lis中数字平方和的函数

我试着写一个平方和(xs)函数来计算列表xs中数字的平方和。例如,平方和([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))

但它似乎没有正确地对正整数的值-我不确定它在做什么。请参见本屏幕截图中的Visualize Python演练。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值