如果列表“ x”包含负值,我想计算谐波平均值并引发异常。 但是代码不起作用。如果要解决问题,如何调整我的 for + ? 谢谢。
x=[1,2,3.0,-3,,-2,1]
def hmean(x):
sum= 0.0
for i in x:
if i < 0:
raise Exception("list contains negative values")
else:
sum = 0.0
for i in x:
sum+= 1.0 / i
return print(float(len(x) / sum))
答案 0 :(得分:2)
此代码存在几个问题:
def hmean(x):
for i in x:
if i < 0:
raise Exception("list contains negative values")
# no need for else:, we come here if exception is not raised
s = 0.0 # do not use sum as variable name
for i in x:
s += 1.0 / i
return float(len(x)) / s # return needs to be outside the for loop; also, no print() here
答案 1 :(得分:1)
您好,如果您想更正答案,认为会有所帮助:
x=[1,2,3.0,-3,2,-2,1]
def hmean(x):
s= 0.0
for i in x:
if i < 0:
raise Exception("list contains negative values")
else:
s += 1.0 / i
return float(len(x) / sum)
hm = hmean(x)
print(hm)