From 9c8c26f467cefc7abcab03f85eb053a52c790442 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Mon, 7 Aug 2023 06:46:23 -0400 Subject: [PATCH] Fixes from code review --- maths/interquartile_range.py | 59 +++++++++++++++++------------------- 1 file changed, 27 insertions(+), 32 deletions(-) diff --git a/maths/interquartile_range.py b/maths/interquartile_range.py index 979a58a8d..1d77c75b2 100644 --- a/maths/interquartile_range.py +++ b/maths/interquartile_range.py @@ -1,10 +1,10 @@ """ -This is the implementation of inter_quartile range (IQR). +An implementation of interquartile range (IQR) which is a measure of statistical +dispersion, which is the spread of the data. -function takes the list of numeric values as input -and return the IQR as output. +The function takes the list of numeric values as input and returns the IQR. -Script inspired from its corresponding Wikipedia article +Script inspired by this Wikipedia article: https://en.wikipedia.org/wiki/Interquartile_range """ from __future__ import annotations @@ -12,52 +12,47 @@ from __future__ import annotations def find_median(nums: list[int | float]) -> float: """ - This is the implementation of median. + 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])) + >>> find_median(nums=([1, 2, 2, 3, 4])) 2 - - >>> find_median(nums=([1,2,2,3,4,4])) + >>> 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 """ - length = len(nums) - if length % 2: - return nums[length // 2] - return float((nums[length // 2] + nums[(length // 2) - 1]) / 2) + div, mod = divmod(len(nums), 2) + if mod: + return nums[div] + return float((nums[div] + nums[(div) - 1]) / 2) def interquartile_range(nums: list[int | float]) -> float: """ - This is the implementation of inter_quartile - range for a list of numeric. - :param nums: The list of data point - :return: Inter_quartile range + 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]) + >>> 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. - - >>> 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(nums) - if length == 0: + if not nums: raise ValueError("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))