我正在尝试编写一个函数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))
但它似乎没有正确地平衡整数的值 - 我不确定它在做什么。请参阅演练的此屏幕截图Visualize Python。
答案 0 :(得分:5)
def sum_of_squares(xs):
return sum(x * x for x in xs)
答案 1 :(得分:3)
import random
xs = []
for i in range(3):
xs.append(random.randint(0,50))
def sum_of_squares(xs):
sum_of_squares=0 #mistake 1 : initialize sum first. you are making new sum variable in loop everytime.
for i in (xs):
squared = i * i #mistake 2 : ** is exponent and not multiply.
sum_of_squares += squared #mistake 3
return sum_of_squares
print (sum_of_squares(xs))
答案 2 :(得分:1)
首先在纸上概念这个概念。
你必须解析List,做正方形并将其保存到某个变量。
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):
result = 0
for i in xs:
result += i*i
return result