【问题标题】:Function That Computes Sum of Squares of Numbers in List计算列表中数字平方和的函数
【发布时间】: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 * ii ** 2。 --- i 甚至应该从该函数内部可见吗?它是一个全局整数。

标签: python list function integer


【解决方案1】:

你正在犯愚蠢的错误。试试这个:

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))

【讨论】:

  • 为什么我们使用sum_of_squares=0来初始化sum?第二个错误是有道理的,很容易解决。谢谢。
  • 您所做的是在循环内声明 sum_of_squares ,因此在每次迭代中它都声明它是新鲜的并进行计算,但您需要的是总和,而不仅仅是最后一次迭代。加上错误#3是错误#2下面的加法公式。
  • 所以如果我们有 [13, 31, 20] 它会返回 sum_of_squares 为 400?错误 #3 是有道理的。
  • 如果您按照自己的方式进行操作,它将返回 3*squared。平方是 i**i,即 20^20。太出乎意料了。
【解决方案2】:
def sum_of_squares(xs):
    return sum(x * x for x in xs)

【讨论】:

  • 这个解决方案非常好。不过,我认为提问者会更难理解。
  • 同意布兰登。考虑在你的回答中解释为什么它是更好的方法。
【解决方案3】:

首先在纸上正确的概念。

  1. 您有号码列表。
  2. 你必须解析列表,做正方形并将其保存到某个变量中。

    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
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2011-06-07
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2012-10-24
    • 2017-04-15
    相关资源
    最近更新 更多