forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterquartile_range.py
67 lines (56 loc) · 1.85 KB
/
interquartile_range.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
An implementation of interquartile range (IQR) which is a measure of statistical
dispersion, which is the spread of the data.
The function takes the list of numeric values as input and returns the IQR.
Script inspired by this Wikipedia article:
https://en.wikipedia.org/wiki/Interquartile_range
"""
from __future__ importannotations
deffind_median(nums: list[int|float]) ->float:
"""
This is the implementation of the median.
:param nums: The list of numeric nums
:return: Median of the list
>>> find_median(nums=([1, 2, 2, 3, 4]))
2
>>> find_median(nums=([1, 2, 2, 3, 4, 4]))
2.5
>>> find_median(nums=([-1, 2, 0, 3, 4, -4]))
1.5
>>> find_median(nums=([1.1, 2.2, 2, 3.3, 4.4, 4]))
2.65
"""
div, mod=divmod(len(nums), 2)
ifmod:
returnnums[div]
return (nums[div] +nums[(div) -1]) /2
definterquartile_range(nums: list[int|float]) ->float:
"""
Return the interquartile range for a list of numeric values.
:param nums: The list of numeric values.
:return: interquartile range
>>> interquartile_range(nums=[4, 1, 2, 3, 2])
2.0
>>> interquartile_range(nums = [-2, -7, -10, 9, 8, 4, -67, 45])
17.0
>>> interquartile_range(nums = [-2.1, -7.1, -10.1, 9.1, 8.1, 4.1, -67.1, 45.1])
17.2
>>> interquartile_range(nums = [0, 0, 0, 0, 0])
0.0
>>> interquartile_range(nums=[])
Traceback (most recent call last):
...
ValueError: The list is empty. Provide a non-empty list.
"""
ifnotnums:
raiseValueError("The list is empty. Provide a non-empty list.")
nums.sort()
length=len(nums)
div, mod=divmod(length, 2)
q1=find_median(nums[:div])
half_length=sum((div, mod))
q3=find_median(nums[half_length:length])
returnq3-q1
if__name__=="__main__":
importdoctest
doctest.testmod()