Skip to content

Commit 71e902d

Browse files
authored
Merge pull request #2751 from rrbharath/feat/chebyshev-distance-algorithm
feat(math): add chebyshev distance
2 parents 6dfba95 + 70a5e76 commit 71e902d

3 files changed

Lines changed: 42 additions & 0 deletions

File tree

algorithms/math/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
modular_inverse, # type: ignore[no-redef] # noqa: E402
1313
)
1414
from algorithms.math.base_conversion import base_to_int, int_to_base
15+
from algorithms.math.chebyshev_distance import chebyshev_distance
1516
from algorithms.math.combination import combination, combination_memo
1617
from algorithms.math.cosine_similarity import cosine_similarity
1718
from algorithms.math.decimal_to_binary_ip import (
@@ -66,6 +67,7 @@
6667
__all__ = [
6768
"base_to_int",
6869
"int_to_base",
70+
"chebyshev_distance",
6971
"chinese_remainder_theorem",
7072
"combination",
7173
"combination_memo",
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""Chebyshev distance — L-infinity distance between two points.
2+
3+
Also known as chessboard distance, it is the maximum absolute difference
4+
across coordinates. In chess, it is the minimum number of moves a king
5+
needs to travel between two squares.
6+
"""
7+
8+
from __future__ import annotations
9+
10+
11+
def chebyshev_distance(a: tuple[float, ...], b: tuple[float, ...]) -> float:
12+
"""Return the Chebyshev (L-infinity) distance between points *a* and *b*.
13+
14+
Works in any number of dimensions.
15+
16+
>>> chebyshev_distance((1, 2, 3), (4, 5, 6))
17+
3
18+
>>> chebyshev_distance((1, 2), (1, 2))
19+
0
20+
>>> chebyshev_distance((-1, -2), (4, 3))
21+
5
22+
"""
23+
if len(a) != len(b):
24+
msg = "Points must have the same number of dimensions."
25+
raise ValueError(msg)
26+
return max(abs(x - y) for x, y in zip(a, b, strict=False))

tests/test_math.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from algorithms.math import (
66
base_to_int,
7+
chebyshev_distance,
78
chinese_remainder_theorem,
89
combination,
910
combination_memo,
@@ -616,6 +617,19 @@ def test_complex_numbers(self):
616617
self.assertEqual(real, real_result)
617618
self.assertEqual(imag, imag_result)
618619

620+
class TestChebyshevDistance(unittest.TestCase):
621+
"""[summary]
622+
Test for the file chebyshev_distance.py
623+
624+
Arguments:
625+
unittest {[type]} -- [description]
626+
"""
627+
628+
def test_chebyshev_distance(self):
629+
self.assertEqual(3, chebyshev_distance([1, 2, 3], [4, 5, 6]))
630+
self.assertEqual(0, chebyshev_distance([1, 2], [1, 2]))
631+
self.assertEqual(5, chebyshev_distance([-1, -2], [4, 3]))
632+
619633

620634
if __name__ == "__main__":
621635
unittest.main()

0 commit comments

Comments
 (0)