TheAlgorithms-Python

Форк
0
/
interquartile_range.py 
67 строк · 1.8 Кб
1
"""
2
An implementation of interquartile range (IQR) which is a measure of statistical
3
dispersion, which is the spread of the data.
4

5
The function takes the list of numeric values as input and returns the IQR.
6

7
Script inspired by this Wikipedia article:
8
https://en.wikipedia.org/wiki/Interquartile_range
9
"""
10

11
from __future__ import annotations
12

13

14
def find_median(nums: list[int | float]) -> float:
15
    """
16
    This is the implementation of the median.
17
    :param nums: The list of numeric nums
18
    :return: Median of the list
19
    >>> find_median(nums=([1, 2, 2, 3, 4]))
20
    2
21
    >>> find_median(nums=([1, 2, 2, 3, 4, 4]))
22
    2.5
23
    >>> find_median(nums=([-1, 2, 0, 3, 4, -4]))
24
    1.5
25
    >>> find_median(nums=([1.1, 2.2, 2, 3.3, 4.4, 4]))
26
    2.65
27
    """
28
    div, mod = divmod(len(nums), 2)
29
    if mod:
30
        return nums[div]
31
    return (nums[div] + nums[(div) - 1]) / 2
32

33

34
def interquartile_range(nums: list[int | float]) -> float:
35
    """
36
    Return the interquartile range for a list of numeric values.
37
    :param nums: The list of numeric values.
38
    :return: interquartile range
39

40
    >>> interquartile_range(nums=[4, 1, 2, 3, 2])
41
    2.0
42
    >>> interquartile_range(nums = [-2, -7, -10, 9, 8, 4, -67, 45])
43
    17.0
44
    >>> interquartile_range(nums = [-2.1, -7.1, -10.1, 9.1, 8.1, 4.1, -67.1, 45.1])
45
    17.2
46
    >>> interquartile_range(nums = [0, 0, 0, 0, 0])
47
    0.0
48
    >>> interquartile_range(nums=[])
49
    Traceback (most recent call last):
50
    ...
51
    ValueError: The list is empty. Provide a non-empty list.
52
    """
53
    if not nums:
54
        raise ValueError("The list is empty. Provide a non-empty list.")
55
    nums.sort()
56
    length = len(nums)
57
    div, mod = divmod(length, 2)
58
    q1 = find_median(nums[:div])
59
    half_length = sum((div, mod))
60
    q3 = find_median(nums[half_length:length])
61
    return q3 - q1
62

63

64
if __name__ == "__main__":
65
    import doctest
66

67
    doctest.testmod()
68

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

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

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

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