python-checkio/OReilly/median.py

31 lines
1.0 KiB
Python
Raw Normal View History

2020-01-03 14:31:18 +01:00
from typing import List
import math
def checkio(data: List[int]) -> [int, float]:
data.sort()
data_len = len(data)
if data_len % 2 == 0:
if data_len != 2:
cut = int(data_len / 2 - 1)
data = data[cut:-cut]
return sum(data) / len(data)
middle = math.floor(data_len / 2)
return data[middle]
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print("Example:")
print(checkio([1, 2, 3, 4, 5]))
assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"
assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list"
assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average"
assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"
print("Start the long test")
assert checkio(list(range(1000000))) == 499999.5, "Long."
assert checkio([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == 5, "5."
assert checkio([999999, 1]) == 5, "5."
print("Coding complete? Click 'Check' to earn cool rewards!")