MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / manhattan_distance

Function manhattan_distance

maths/manhattan_distance.py:1–43  ·  view source on GitHub ↗

Expectts two list of numbers representing two points in the same n-dimensional space https://en.wikipedia.org/wiki/Taxicab_geometry >>> manhattan_distance([1,1], [2,2]) 2.0 >>> manhattan_distance([1.5,1.5], [2,2]) 1.0 >>> manhattan_distance([1.5,1.5], [2.5,2])

(point_a: list, point_b: list)

Source from the content-addressed store, hash-verified

1def manhattan_distance(point_a: list, point_b: list) -> float:
2 """
3 Expectts two list of numbers representing two points in the same
4 n-dimensional space
5
6 https://en.wikipedia.org/wiki/Taxicab_geometry
7
8 >>> manhattan_distance([1,1], [2,2])
9 2.0
10 >>> manhattan_distance([1.5,1.5], [2,2])
11 1.0
12 >>> manhattan_distance([1.5,1.5], [2.5,2])
13 1.5
14 >>> manhattan_distance([-3, -3, -3], [0, 0, 0])
15 9.0
16 >>> manhattan_distance([1,1], None)
17 Traceback (most recent call last):
18 ...
19 ValueError: Missing an input
20 >>> manhattan_distance([1,1], [2, 2, 2])
21 Traceback (most recent call last):
22 ...
23 ValueError: Both points must be in the same n-dimensional space
24 >>> manhattan_distance([1,"one"], [2, 2, 2])
25 Traceback (most recent call last):
26 ...
27 TypeError: Expected a list of numbers as input, found str
28 >>> manhattan_distance(1, [2, 2, 2])
29 Traceback (most recent call last):
30 ...
31 TypeError: Expected a list of numbers as input, found int
32 >>> manhattan_distance([1,1], "not_a_list")
33 Traceback (most recent call last):
34 ...
35 TypeError: Expected a list of numbers as input, found str
36 """
37
38 _validate_point(point_a)
39 _validate_point(point_b)
40 if len(point_a) != len(point_b):
41 raise ValueError("Both points must be in the same n-dimensional space")
42
43 return float(sum(abs(a - b) for a, b in zip(point_a, point_b)))
44
45
46def _validate_point(point: list[float]) -> None:

Callers

nothing calls this directly

Calls 1

_validate_pointFunction · 0.85

Tested by

no test coverage detected