From eda857eb9be8bee43085496d16e18f55aba75012 Mon Sep 17 00:00:00 2001 From: dbring Date: Sun, 8 Oct 2023 14:39:03 -0700 Subject: [PATCH 1/2] Added the Chebyshev distance function --- maths/chebyshev_distance.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 maths/chebyshev_distance.py diff --git a/maths/chebyshev_distance.py b/maths/chebyshev_distance.py new file mode 100644 index 000000000000..d13d8d721735 --- /dev/null +++ b/maths/chebyshev_distance.py @@ -0,0 +1,20 @@ +def chebyshev_distance(point_a: list[float], point_b: list[float]) -> float: + """ + This function calculates the Chebyshev distance (also known as the + Chessboard distance) between two n-dimensional points represented as lists. + + https://en.wikipedia.org/wiki/Chebyshev_distance + + >>> chebyshev_distance([1.0, 1.0], [2.0, 2.0]) + 1.0 + >>> chebyshev_distance([1.0, 1.0, 9.0], [2.0, 2.0, -5.2]) + 14.2 + >>> chebyshev_distance([1.0], [2.0, 2.0]) + Traceback (most recent call last): + ... + Exception: Both points must have the same dimension. + """ + if len(point_a) != len(point_b): + raise Exception("Both points must have the same dimension.") + + return float(max(abs(a - b) for a, b in zip(point_a, point_b))) From e35c53c0de3feed78a911bdc5bf959f036aca2f7 Mon Sep 17 00:00:00 2001 From: dbring Date: Mon, 9 Oct 2023 13:01:26 -0700 Subject: [PATCH 2/2] Remove float cast and made error handling more precise --- maths/chebyshev_distance.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/maths/chebyshev_distance.py b/maths/chebyshev_distance.py index d13d8d721735..4801d391621f 100644 --- a/maths/chebyshev_distance.py +++ b/maths/chebyshev_distance.py @@ -12,9 +12,9 @@ def chebyshev_distance(point_a: list[float], point_b: list[float]) -> float: >>> chebyshev_distance([1.0], [2.0, 2.0]) Traceback (most recent call last): ... - Exception: Both points must have the same dimension. + ValueError: Both points must have the same dimension. """ if len(point_a) != len(point_b): - raise Exception("Both points must have the same dimension.") + raise ValueError("Both points must have the same dimension.") - return float(max(abs(a - b) for a, b in zip(point_a, point_b))) + return max(abs(a - b) for a, b in zip(point_a, point_b))