TheAlgorithms-Python

Форк
0
/
euclidean_distance.py 
65 строк · 1.9 Кб
1
from __future__ import annotations
2

3
import typing
4
from collections.abc import Iterable
5

6
import numpy as np
7

8
Vector = typing.Union[Iterable[float], Iterable[int], np.ndarray]  # noqa: UP007
9
VectorOut = typing.Union[np.float64, int, float]  # noqa: UP007
10

11

12
def euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut:
13
    """
14
    Calculate the distance between the two endpoints of two vectors.
15
    A vector is defined as a list, tuple, or numpy 1D array.
16
    >>> euclidean_distance((0, 0), (2, 2))
17
    2.8284271247461903
18
    >>> euclidean_distance(np.array([0, 0, 0]), np.array([2, 2, 2]))
19
    3.4641016151377544
20
    >>> euclidean_distance(np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]))
21
    8.0
22
    >>> euclidean_distance([1, 2, 3, 4], [5, 6, 7, 8])
23
    8.0
24
    """
25
    return np.sqrt(np.sum((np.asarray(vector_1) - np.asarray(vector_2)) ** 2))
26

27

28
def euclidean_distance_no_np(vector_1: Vector, vector_2: Vector) -> VectorOut:
29
    """
30
    Calculate the distance between the two endpoints of two vectors without numpy.
31
    A vector is defined as a list, tuple, or numpy 1D array.
32
    >>> euclidean_distance_no_np((0, 0), (2, 2))
33
    2.8284271247461903
34
    >>> euclidean_distance_no_np([1, 2, 3, 4], [5, 6, 7, 8])
35
    8.0
36
    """
37
    return sum((v1 - v2) ** 2 for v1, v2 in zip(vector_1, vector_2)) ** (1 / 2)
38

39

40
if __name__ == "__main__":
41

42
    def benchmark() -> None:
43
        """
44
        Benchmarks
45
        """
46
        from timeit import timeit
47

48
        print("Without Numpy")
49
        print(
50
            timeit(
51
                "euclidean_distance_no_np([1, 2, 3], [4, 5, 6])",
52
                number=10000,
53
                globals=globals(),
54
            )
55
        )
56
        print("With Numpy")
57
        print(
58
            timeit(
59
                "euclidean_distance([1, 2, 3], [4, 5, 6])",
60
                number=10000,
61
                globals=globals(),
62
            )
63
        )
64

65
    benchmark()
66

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.