Author WarrenWeckesser
Recipients WarrenWeckesser
Date 2019-10-06.01:46:18
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
The function statistics.harmonic_mean is supposed to raise a StatisticsError if any element in the input is negative.  It fails to do so if the negative element is preceded by a zero.  When there is a zero before the negative element, the function returns 0:

>>> from statistics import harmonic_mean
>>> harmonic_mean([0, -1, 3])

If the zero occurs after the negative value, the StatisticsError exception is correctly raised:

>>> harmonic_mean([-1, 0, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/warren/repos/git/forks/cpython/Lib/", line 406, in harmonic_mean
    T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
  File "/Users/warren/repos/git/forks/cpython/Lib/", line 164, in _sum
    for typ, values in groupby(data, type):
  File "/Users/warren/repos/git/forks/cpython/Lib/", line 406, in <genexpr>
    T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
  File "/Users/warren/repos/git/forks/cpython/Lib/", line 289, in _fail_neg
    raise StatisticsError(errmsg)
statistics.StatisticsError: harmonic mean does not support negative values

The problem is in this code in the function harmonic_mean:

        T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
    except ZeroDivisionError:
        return 0

When the zero occurs before the negative value, the ZeroDivisionError is raised before the negative value has been seen by the generator _fail_neg, and the function returns 0.
Date User Action Args
2019-10-06 01:46:18WarrenWeckessersetrecipients: + WarrenWeckesser
2019-10-06 01:46:18WarrenWeckessersetmessageid: <>
2019-10-06 01:46:18WarrenWeckesserlinkissue38382 messages
2019-10-06 01:46:18WarrenWeckessercreate