MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / interquartile_range

Function interquartile_range

maths/interquartile_range.py:34–61  ·  view source on GitHub ↗

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 >>> interquartil

(nums: list[int | float])

Source from the content-addressed store, hash-verified

32
33
34def interquartile_range(nums: list[int | float]) -> float:
35 """
36 Return 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])
41 2.0
42 >>> interquartile_range(nums = [-2, -7, -10, 9, 8, 4, -67, 45])
43 17.0
44 >>> interquartile_range(nums = [-2.1, -7.1, -10.1, 9.1, 8.1, 4.1, -67.1, 45.1])
45 17.2
46 >>> interquartile_range(nums = [0, 0, 0, 0, 0])
47 0.0
48 >>> interquartile_range(nums=[])
49 Traceback (most recent call last):
50 ...
51 ValueError: The list is empty. Provide a non-empty list.
52 """
53 if not nums:
54 raise ValueError("The list is empty. Provide a non-empty list.")
55 nums.sort()
56 length = len(nums)
57 div, mod = divmod(length, 2)
58 q1 = find_median(nums[:div])
59 half_length = sum((div, mod))
60 q3 = find_median(nums[half_length:length])
61 return q3 - q1
62
63
64if __name__ == "__main__":

Callers

nothing calls this directly

Calls 2

find_medianFunction · 0.85
sortMethod · 0.80

Tested by

no test coverage detected