From c8d6ce5708b1e3675e15e4b73302562ae47e0442 Mon Sep 17 00:00:00 2001 From: Akash Date: Tue, 11 Aug 2026 22:11:48 +0530 Subject: [PATCH 1/3] Add harmonic mean algorithm --- maths/harmonic_mean.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 maths/harmonic_mean.py diff --git a/maths/harmonic_mean.py b/maths/harmonic_mean.py new file mode 100644 index 000000000000..91e63ab91138 --- /dev/null +++ b/maths/harmonic_mean.py @@ -0,0 +1,33 @@ +from __future__ import annotations + + +def harmonic_mean(numbers: list[int | float]) -> float: + """ + Return the harmonic mean of a sequence of numbers. + + >>> harmonic_mean([1, 2, 4]) + 1.7142857142857142 + >>> harmonic_mean([2, 2, 2]) + 2.0 + >>> harmonic_mean([]) + Traceback (most recent call last): + ... + ValueError: harmonic_mean() arg is an empty sequence + >>> harmonic_mean([1, 0, 2]) + Traceback (most recent call last): + ... + ValueError: harmonic mean is undefined for zero values + """ + if not numbers: + raise ValueError("harmonic_mean() arg is an empty sequence") + + if any(number == 0 for number in numbers): + raise ValueError("harmonic mean is undefined for zero values") + + return len(numbers) / sum(1 / number for number in numbers) + + +if __name__ == "__main__": + import doctest + + doctest.testmod(verbose=True) \ No newline at end of file From c22f999c0f29eb08ec5a22ef8d751d07a6add084 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 11 Aug 2026 16:45:56 +0000 Subject: [PATCH 2/3] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- maths/harmonic_mean.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/harmonic_mean.py b/maths/harmonic_mean.py index 91e63ab91138..95d03f81df18 100644 --- a/maths/harmonic_mean.py +++ b/maths/harmonic_mean.py @@ -30,4 +30,4 @@ def harmonic_mean(numbers: list[int | float]) -> float: if __name__ == "__main__": import doctest - doctest.testmod(verbose=True) \ No newline at end of file + doctest.testmod(verbose=True) From 6e06c09f07b351f0659f9ede2a442a643fb5a077 Mon Sep 17 00:00:00 2001 From: Akash Date: Tue, 11 Aug 2026 22:20:24 +0530 Subject: [PATCH 3/3] Add harmonic mean reference --- maths/harmonic_mean.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/maths/harmonic_mean.py b/maths/harmonic_mean.py index 95d03f81df18..8bfbc486e836 100644 --- a/maths/harmonic_mean.py +++ b/maths/harmonic_mean.py @@ -5,6 +5,8 @@ def harmonic_mean(numbers: list[int | float]) -> float: """ Return the harmonic mean of a sequence of numbers. + Reference: https://en.wikipedia.org/wiki/Harmonic_mean + >>> harmonic_mean([1, 2, 4]) 1.7142857142857142 >>> harmonic_mean([2, 2, 2])