Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Practical solution in Clear category for Median by PositronicLlama
"""
Compute the median of a list of numbers.
"""
import heapq
def checkio(data):
"""Return the median of a list of numbers."""
# A linear median finding algorithm such as "median of medians" may be faster
# theoretically, but using the builtin sort is faster in practice for the
# sizes of data set encountered in the tests.
#
# The 'heapq' module also offers nlargest and nsmallest methods, which can
# be used to find a median, but even for lists of 100 elements, sort is ~3x
# faster according to the timeit module.
data.sort()
l = len(data)
mid = l // 2
if l % 2 == 1:
# If the length of the list is odd, return the middle item.
return data[mid]
else:
# If the length is even, average the two items bracketing the middle.
return sum(data[mid-1:mid+1]) / 2
if __name__ == '__main__':
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"
June 1, 2013
Comments: