TheAlgorithms-Python
65 строк · 1.9 Кб
1from __future__ import annotations2
3import typing4from collections.abc import Iterable5
6import numpy as np7
8Vector = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP0079VectorOut = typing.Union[np.float64, int, float] # noqa: UP00710
11
12def euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut:13"""14Calculate the distance between the two endpoints of two vectors.
15A vector is defined as a list, tuple, or numpy 1D array.
16>>> euclidean_distance((0, 0), (2, 2))
172.8284271247461903
18>>> euclidean_distance(np.array([0, 0, 0]), np.array([2, 2, 2]))
193.4641016151377544
20>>> euclidean_distance(np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]))
218.0
22>>> euclidean_distance([1, 2, 3, 4], [5, 6, 7, 8])
238.0
24"""
25return np.sqrt(np.sum((np.asarray(vector_1) - np.asarray(vector_2)) ** 2))26
27
28def euclidean_distance_no_np(vector_1: Vector, vector_2: Vector) -> VectorOut:29"""30Calculate the distance between the two endpoints of two vectors without numpy.
31A vector is defined as a list, tuple, or numpy 1D array.
32>>> euclidean_distance_no_np((0, 0), (2, 2))
332.8284271247461903
34>>> euclidean_distance_no_np([1, 2, 3, 4], [5, 6, 7, 8])
358.0
36"""
37return sum((v1 - v2) ** 2 for v1, v2 in zip(vector_1, vector_2)) ** (1 / 2)38
39
40if __name__ == "__main__":41
42def benchmark() -> None:43"""44Benchmarks
45"""
46from timeit import timeit47
48print("Without Numpy")49print(50timeit(51"euclidean_distance_no_np([1, 2, 3], [4, 5, 6])",52number=10000,53globals=globals(),54)55)56print("With Numpy")57print(58timeit(59"euclidean_distance([1, 2, 3], [4, 5, 6])",60number=10000,61globals=globals(),62)63)64
65benchmark()66