- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个函数 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演练。
最佳答案
def sum_of_squares(xs):
return sum(x * x for x in xs)
关于python - 计算列表中数字平方和的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40918917/
尝试构造一段代码,返回range(1, limit)中的一个数是否为两个平方数之和(平方数如1**2 = 1,2**2 = 4 - 所以我试图分配给一个数字列表,它们是否是任何这些平方数的总和组合 -
我确实有一个矩阵,行中包含观察值(不同 pH 下的测量值),数据点作为列(随时间变化的浓度)。因此,一行包含一个 pH 值的不同数据点。 我确实想对数据拟合 ODE。所以我定义了一个成本函数,并想计算
令我惊讶的是,调用 np.inner 计算平方和比在预先计算的平方数组上调用 np.sum 快大约 5 倍: 对这种行为有什么见解吗?实际上,我对平方和的快速实现很感兴趣,因此也欢迎提出这些想法。 最
我使用lm(x~y1 + y1 + ... + yn)估计了线性回归模型,并为了应对当前的异方差性,我让 R 估计了稳健的标准误差 coeftest(model, vcov = vcovHC(mode
我使用lm(x~y1 + y1 + ... + yn)估计了线性回归模型,并为了应对当前的异方差性,我让 R 估计了稳健的标准误差 coeftest(model, vcov = vcovHC(mode
我是一名优秀的程序员,十分优秀!