3 回答
TA贡献1816条经验 获得超4个赞
我不知道为什么不允许您使用内置函数,但我想您可以在没有内置函数的情况下做到这一点,如下所示:
def mean_variance(numbers):
meanSum = 0
for num in numbers:
meanSum += num
mean = meanSum / len(numbers)
varSum = 0
for num in numbers:
varSum += (num - mean) ** 2
var = varSum / (len(numbers) - 1)
return mean, var
TA贡献1810条经验 获得超4个赞
我用 替换了该sum函数reduce并更正了公式中的错误。这是代码:
from functools import reduce
def mean_variance(numbers):
m = reduce(lambda x, y: x+y, numbers) / len(numbers)
var = reduce(lambda x, y: x+y, ((xi - m) ** 2 for xi in numbers)) / (len(numbers)-1)
return m, var
TA贡献1864条经验 获得超6个赞
不使用任何内置方法
平均值和方差可以是浮点数。所以返回int或float将由自动处理assert
def mean_variance(inputList):
sum = 0
lenList = 0
for val in inputList:
sum = int(val) + sum
lenList = lenList + 1
mean = sum/lenList
sum_sq = 0
for val in inputList:
sq = (int(val) - int(mean)) ** 2
sum_sq = sum_sq + sq
variance = sum_sq/(lenList-1)
return (float(mean), float(variance))
print(mean_variance([1, 2, 3]))
assert mean_variance([1, 2, 3]) == (2, 1)
添加回答
举报