BugLab011 / 020up to 100
listssortingmethodsgotchaeasy

Sorted by Nothing

The function get_median(numbers) should return the median value of a list of numbers. For odd-length lists, the median is the middle element; for even-length lists, it is the average of the two middle elements.

The function crashes immediately on any input with a TypeError.

Can you find the single-word fix that makes it work?

# your fix
+ must call sorted()
hint 2after hint 1
hint 3after hint 2
solution

Read the code. Before running anything: what does the last line below give?

def get_median(numbers):
"""
Returns the median value of a list of numbers.
For odd-length lists, returns the middle element.
For even-length lists, returns the average of the two middle elements.
Example: get_median([3, 1, 4, 1, 5]) -> 3
"""
sorted_nums = numbers.sort()
n = len(numbers)
if n % 2 == 1:
return sorted_nums[n // 2]
else:
return (sorted_nums[n // 2 - 1] + sorted_nums[n // 2]) / 2
>>> get_median([3, 1, 4])