【发布时间】:2017-04-16 13:54:45
【问题描述】:
我正在尝试编写一个函数 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 演练的此屏幕截图。
【问题讨论】:
-
squared = i ** i是错误的。您的意思是i * i或i ** 2。 ---i甚至应该从该函数内部可见吗?它是一个全局整数。
标签: python list function integer