mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-24 05:21:09 +00:00
Update average_median.py (#998)
added doctest, fixed TypeError: list indices must be integers or slices, not float error due to number/2 producing float as index.
This commit is contained in:
parent
897f1d0fb4
commit
37fbd8ca2e
|
@ -1,41 +1,34 @@
|
||||||
"""
|
|
||||||
Find median of a list of numbers.
|
|
||||||
|
|
||||||
Read more about medians:
|
|
||||||
https://en.wikipedia.org/wiki/Median
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def median(nums):
|
def median(nums):
|
||||||
"""Find median of a list of numbers."""
|
"""
|
||||||
# Sort list
|
Find median of a list of numbers.
|
||||||
sorted_list = sorted(nums)
|
|
||||||
print("List of numbers:")
|
|
||||||
print(sorted_list)
|
|
||||||
|
|
||||||
# Is number of items in list even?
|
>>> median([0])
|
||||||
|
0
|
||||||
|
>>> median([4,1,3,2])
|
||||||
|
2.5
|
||||||
|
|
||||||
|
Args:
|
||||||
|
nums: List of nums
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Median.
|
||||||
|
"""
|
||||||
|
sorted_list = sorted(nums)
|
||||||
|
med = None
|
||||||
if len(sorted_list) % 2 == 0:
|
if len(sorted_list) % 2 == 0:
|
||||||
# Find index for first middle value.
|
mid_index_1 = len(sorted_list) // 2
|
||||||
mid_index_1 = len(sorted_list) / 2
|
mid_index_2 = (len(sorted_list) // 2) - 1
|
||||||
# Find index for second middle value.
|
|
||||||
mid_index_2 = -(len(sorted_list) / 2) - 1
|
|
||||||
# Divide middle values by 2 to get average (mean).
|
|
||||||
med = (sorted_list[mid_index_1] + sorted_list[mid_index_2]) / float(2)
|
med = (sorted_list[mid_index_1] + sorted_list[mid_index_2]) / float(2)
|
||||||
return med # Return makes `else:` unnecessary.
|
else:
|
||||||
# Number of items is odd.
|
mid_index = (len(sorted_list) - 1) // 2
|
||||||
mid_index = (len(sorted_list) - 1) / 2
|
med = sorted_list[mid_index]
|
||||||
# Middle index is median.
|
|
||||||
med = sorted_list[mid_index]
|
|
||||||
return med
|
return med
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Call average module to find median of a specific list of numbers."""
|
|
||||||
print("Odd number of numbers:")
|
print("Odd number of numbers:")
|
||||||
print(median([2, 4, 6, 8, 20, 50, 70]))
|
print(median([2, 4, 6, 8, 20, 50, 70]))
|
||||||
print("Even number of numbers:")
|
print("Even number of numbers:")
|
||||||
print(median([2, 4, 6, 8, 20, 50]))
|
print(median([2, 4, 6, 8, 20, 50]))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user