2023-07-02 20:08:30 +05:30
|
|
|
"""
|
|
|
|
This is the implementation of inter_quartile range (IQR).
|
|
|
|
|
|
|
|
function takes the list of numeric values as input
|
|
|
|
and return the IQR as output.
|
|
|
|
|
|
|
|
Script inspired from its corresponding Wikipedia article
|
|
|
|
https://en.wikipedia.org/wiki/Interquartile_range
|
|
|
|
"""
|
2023-08-06 23:38:17 +05:30
|
|
|
from __future__ import annotations
|
2023-07-02 20:08:30 +05:30
|
|
|
|
|
|
|
|
2023-08-06 23:38:17 +05:30
|
|
|
def find_median(nums: list[int | float]) -> float:
|
2023-07-02 20:08:30 +05:30
|
|
|
"""
|
|
|
|
This is the implementation of median.
|
2023-08-06 23:38:17 +05:30
|
|
|
:param nums: The list of numeric nums
|
2023-07-02 20:08:30 +05:30
|
|
|
:return: Median of the list
|
2023-08-06 23:38:17 +05:30
|
|
|
>>> find_median(nums=([1,2,2,3,4]))
|
2023-07-02 20:08:30 +05:30
|
|
|
2
|
|
|
|
|
2023-08-06 23:38:17 +05:30
|
|
|
>>> find_median(nums=([1,2,2,3,4,4]))
|
2023-07-02 20:08:30 +05:30
|
|
|
2.5
|
|
|
|
|
|
|
|
|
|
|
|
"""
|
2023-08-06 23:38:17 +05:30
|
|
|
length = len(nums)
|
2023-07-02 20:08:30 +05:30
|
|
|
if length % 2:
|
2023-08-06 23:38:17 +05:30
|
|
|
return nums[length // 2]
|
|
|
|
return float((nums[length // 2] + nums[(length // 2) - 1]) / 2)
|
2023-07-02 20:08:30 +05:30
|
|
|
|
|
|
|
|
2023-08-06 23:38:17 +05:30
|
|
|
def interquartile_range(nums: list[int | float]) -> float:
|
2023-07-02 20:08:30 +05:30
|
|
|
"""
|
|
|
|
This is the implementation of inter_quartile
|
|
|
|
range for a list of numeric.
|
2023-08-06 23:38:17 +05:30
|
|
|
:param nums: The list of data point
|
2023-07-02 20:08:30 +05:30
|
|
|
:return: Inter_quartile range
|
|
|
|
|
2023-08-06 23:38:17 +05:30
|
|
|
>>> interquartile_range(nums=[4,1,2,3,2])
|
2023-07-02 20:08:30 +05:30
|
|
|
2.0
|
|
|
|
|
2023-08-02 00:23:54 +05:30
|
|
|
|
2023-08-06 23:38:17 +05:30
|
|
|
>>> interquartile_range(nums=[])
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: The list is empty. Provide a non-empty list.
|
|
|
|
|
|
|
|
>>> interquartile_range(nums = [-2,-7,-10,9,8,4, -67, 45])
|
|
|
|
17.0
|
|
|
|
|
|
|
|
>>> interquartile_range(nums = [0,0,0,0,0])
|
|
|
|
0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-07-02 20:08:30 +05:30
|
|
|
"""
|
2023-08-06 23:38:17 +05:30
|
|
|
length = len(nums)
|
2023-07-02 20:08:30 +05:30
|
|
|
if length == 0:
|
2023-08-02 00:23:54 +05:30
|
|
|
raise ValueError("The list is empty. Provide a non-empty list.")
|
2023-08-06 23:38:17 +05:30
|
|
|
nums.sort()
|
2023-08-05 22:14:40 +05:30
|
|
|
div, mod = divmod(length, 2)
|
2023-08-06 23:38:17 +05:30
|
|
|
q1 = find_median(nums[:div])
|
2023-08-05 22:14:40 +05:30
|
|
|
half_length = sum((div, mod))
|
2023-08-06 23:38:17 +05:30
|
|
|
q3 = find_median(nums[half_length:length])
|
2023-07-02 20:08:30 +05:30
|
|
|
return q3 - q1
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|