gpt4 book ai didi

python - 此函数在 Python 中的最短表示

转载 作者:行者123 更新时间:2023-11-28 20:28:43 24 4
gpt4 key购买 nike

equation

目前我有:

def func(points): #Input is a matrix with n lines and 2 columns.
centroid = numpy.mean(points, axis=0)
sum = 0
for point in points:
x = point[0] - centroid[0]
y = point[1] - centorid[1]
sum += x**2 + y**2
return math.sqrt(sum)

最佳答案

有一个用于对序列求和的内置函数,称为 sum(很奇怪)。我们可以使用生成器理解创建数据,并将其直接提供给 sum 函数。因此:

return math.sqrt(sum((p[0]-centroid[0])**2 + (p[1]-centroid[1])**2 for p in points))

关于python - 此函数在 Python 中的最短表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4405968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com