[Tutor] How to handle exceptions raised inside a function?
Steven D'Aprano
steve at pearwood.info
Wed Dec 1 23:11:17 CET 2010
Richard D. Moores wrote:
[...]
>> def harmonic_mean(data):
>> try:
>> m = mean(1.0/x for x in data)
>> except ZeroDivisionError:
>> return 0.0
>> if m == 0.0:
>> return math.copysign(float('inf'), m)
>> return 1/m
>
> math.copysign! Didn't know about that one. But "mean"? It's not a
> built-in function..
No, it's not, it's a function from my stats module.
The naive version is simple:
def mean(data):
return sum(data)/len(data)
My version is a bit more complicated than that, in order to minimize
round-off error and support iterators.
--
Steven
More information about the Tutor
mailing list