mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-30 16:31:08 +00:00
0591968947
* * optimization aliquot_sum * fix bug in average_median * fixup! Format Python code with psf/black push * Update maths/average_median.py * updating DIRECTORY.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
36 lines
581 B
Python
36 lines
581 B
Python
def median(nums):
|
|
"""
|
|
Find median of a list of numbers.
|
|
|
|
>>> 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.
|
|
"""
|
|
sorted_list = sorted(nums)
|
|
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]
|
|
)
|
|
|
|
|
|
def main():
|
|
import doctest
|
|
|
|
doctest.testmod()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|