TheAlgorithms-Python
67 строк · 1.8 Кб
1"""
2An implementation of interquartile range (IQR) which is a measure of statistical
3dispersion, which is the spread of the data.
4
5The function takes the list of numeric values as input and returns the IQR.
6
7Script inspired by this Wikipedia article:
8https://en.wikipedia.org/wiki/Interquartile_range
9"""
10
11from __future__ import annotations
12
13
14def find_median(nums: list[int | float]) -> float:
15"""
16This 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]))
202
21>>> find_median(nums=([1, 2, 2, 3, 4, 4]))
222.5
23>>> find_median(nums=([-1, 2, 0, 3, 4, -4]))
241.5
25>>> find_median(nums=([1.1, 2.2, 2, 3.3, 4.4, 4]))
262.65
27"""
28div, mod = divmod(len(nums), 2)
29if mod:
30return nums[div]
31return (nums[div] + nums[(div) - 1]) / 2
32
33
34def interquartile_range(nums: list[int | float]) -> float:
35"""
36Return 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])
412.0
42>>> interquartile_range(nums = [-2, -7, -10, 9, 8, 4, -67, 45])
4317.0
44>>> interquartile_range(nums = [-2.1, -7.1, -10.1, 9.1, 8.1, 4.1, -67.1, 45.1])
4517.2
46>>> interquartile_range(nums = [0, 0, 0, 0, 0])
470.0
48>>> interquartile_range(nums=[])
49Traceback (most recent call last):
50...
51ValueError: The list is empty. Provide a non-empty list.
52"""
53if not nums:
54raise ValueError("The list is empty. Provide a non-empty list.")
55nums.sort()
56length = len(nums)
57div, mod = divmod(length, 2)
58q1 = find_median(nums[:div])
59half_length = sum((div, mod))
60q3 = find_median(nums[half_length:length])
61return q3 - q1
62
63
64if __name__ == "__main__":
65import doctest
66
67doctest.testmod()
68