New submission from Warren Weckesser <warren.weckes...@gmail.com>:
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]) 0 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/statistics.py", 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/statistics.py", line 164, in _sum for typ, values in groupby(data, type): File "/Users/warren/repos/git/forks/cpython/Lib/statistics.py", 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/statistics.py", 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: try: 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. ---------- components: Library (Lib) messages: 354028 nosy: WarrenWeckesser priority: normal severity: normal status: open title: statistics.harmonic_mean fails to raise error with negative input that follows a 0 type: behavior versions: Python 3.9 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue38382> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com