Compare commits

...

2 Commits

Author SHA1 Message Date
Mitra-babu
0e72de66a5 numpy removed from interquartile_range 2023-08-06 23:40:35 +05:30
Mitra-babu
05644a0750 Changes on interquartile_range 2023-08-06 23:38:17 +05:30

View File

@ -7,51 +7,61 @@ and return the IQR as output.
Script inspired from its corresponding Wikipedia article Script inspired from its corresponding Wikipedia article
https://en.wikipedia.org/wiki/Interquartile_range https://en.wikipedia.org/wiki/Interquartile_range
""" """
from __future__ import annotations
import numpy as np
def find_median(x: np.array) -> float: def find_median(nums: list[int | float]) -> float:
""" """
This is the implementation of median. This is the implementation of median.
:param x: The list of numeric values :param nums: The list of numeric nums
:return: Median of the list :return: Median of the list
>>> find_median(x=np.array([1,2,2,3,4])) >>> find_median(nums=([1,2,2,3,4]))
2 2
>>> find_median(np.array([1,2,2,3,4,4])) >>> find_median(nums=([1,2,2,3,4,4]))
2.5 2.5
""" """
length = len(x) length = len(nums)
if length % 2: if length % 2:
return x[length // 2] return nums[length // 2]
return float((x[length // 2] + x[(length // 2) - 1]) / 2) return float((nums[length // 2] + nums[(length // 2) - 1]) / 2)
def interquartile_range(x: np.array) -> float: def interquartile_range(nums: list[int | float]) -> float:
""" """
This is the implementation of inter_quartile This is the implementation of inter_quartile
range for a list of numeric. range for a list of numeric.
:param x: The list of data point :param nums: The list of data point
:return: Inter_quartile range :return: Inter_quartile range
>>> interquartile_range(x=np.array([4,1,2,3,2])) >>> interquartile_range(nums=[4,1,2,3,2])
2.0 2.0
>>> interquartile_range(x=np.array([25,32,49,21,37,43,27,45,31])) >>> interquartile_range(nums=[])
18.0 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
""" """
length = len(x) length = len(nums)
if length == 0: if length == 0:
raise ValueError("The list is empty. Provide a non-empty list.") raise ValueError("The list is empty. Provide a non-empty list.")
x.sort() nums.sort()
div, mod = divmod(length, 2) div, mod = divmod(length, 2)
q1 = find_median(x[:div]) q1 = find_median(nums[:div])
half_length = sum((div, mod)) half_length = sum((div, mod))
q3 = find_median(x[half_length:length]) q3 = find_median(nums[half_length:length])
return q3 - q1 return q3 - q1