3 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
我不知道為什么不允許您使用內(nèi)置函數(shù),但我想您可以在沒有內(nèi)置函數(shù)的情況下做到這一點(diǎn),如下所示:
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貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
我用 替換了該sum函數(shù)reduce并更正了公式中的錯(cuò)誤。這是代碼:
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貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
不使用任何內(nèi)置方法
平均值和方差可以是浮點(diǎn)數(shù)。所以返回int或float將由自動(dòng)處理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)
添加回答
舉報(bào)