2021-06-14 20:39:51 +00:00
|
|
|
from typing import Union
|
|
|
|
|
|
|
|
|
2021-08-18 10:45:07 +00:00
|
|
|
def median(nums: list) -> Union[int, float]:
|
2019-07-10 20:38:10 +00:00
|
|
|
"""
|
|
|
|
Find median of a list of numbers.
|
2021-06-14 20:39:51 +00:00
|
|
|
Wiki: https://en.wikipedia.org/wiki/Median
|
2019-07-05 08:36:48 +00:00
|
|
|
|
2019-07-10 20:38:10 +00:00
|
|
|
>>> median([0])
|
|
|
|
0
|
2021-08-18 10:45:07 +00:00
|
|
|
>>> median([4, 1, 3, 2])
|
2019-07-10 20:38:10 +00:00
|
|
|
2.5
|
2020-08-21 06:39:03 +00:00
|
|
|
>>> median([2, 70, 6, 50, 20, 8, 4])
|
|
|
|
8
|
2019-07-05 08:36:48 +00:00
|
|
|
|
2019-07-10 20:38:10 +00:00
|
|
|
Args:
|
|
|
|
nums: List of nums
|
2019-07-05 08:36:48 +00:00
|
|
|
|
2019-07-10 20:38:10 +00:00
|
|
|
Returns:
|
|
|
|
Median.
|
|
|
|
"""
|
2019-07-05 08:36:48 +00:00
|
|
|
sorted_list = sorted(nums)
|
2020-08-21 06:39:03 +00:00
|
|
|
length = len(sorted_list)
|
|
|
|
mid_index = length >> 1
|
|
|
|
return (
|
|
|
|
(sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2
|
|
|
|
if length % 2 == 0
|
|
|
|
else sorted_list[mid_index]
|
|
|
|
)
|
2019-07-05 08:36:48 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-07-05 08:36:48 +00:00
|
|
|
def main():
|
2020-08-21 06:39:03 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
2019-07-05 08:36:48 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2019-07-05 08:36:48 +00:00
|
|
|
main()
|