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

Function median

maths/average_median.py:4–31  ·  view source on GitHub ↗

Find median of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Median >>> median([0]) 0 >>> median([4, 1, 3, 2]) 2.5 >>> median([2, 70, 6, 50, 20, 8, 4]) 8 Args: nums: List of nums Returns: Median.

(nums: list)

Source from the content-addressed store, hash-verified

2
3
4def median(nums: list) -> int | float:
5 """
6 Find median of a list of numbers.
7 Wiki: https://en.wikipedia.org/wiki/Median
8
9 >>> median([0])
10 0
11 >>> median([4, 1, 3, 2])
12 2.5
13 >>> median([2, 70, 6, 50, 20, 8, 4])
14 8
15
16 Args:
17 nums: List of nums
18
19 Returns:
20 Median.
21 """
22 # The sorted function returns list[SupportsRichComparisonT@sorted]
23 # which does not support `+`
24 sorted_list: list[int] = sorted(nums)
25 length = len(sorted_list)
26 mid_index = length >> 1
27 return (
28 (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2
29 if length % 2 == 0
30 else sorted_list[mid_index]
31 )
32
33
34def main():

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected