Drill

ProblemsPython › patterns

The middle of the list

mediumpatternsSortingArraysMathPython

A dashboard shows a campaign’s typical daily spend, and “typical” is whatever lands in the middle once the days are sorted.

median_of(values: list<int>) → float

Solve it in the editor →

Where you start

def median_of(values: list[int]) -> float:
    

Worked examples

CallResult
median_of([3, 1, 2])2.0
median_of([1, 2])1.5
median_of([5])5.0
median_of([5, 1, 4, 2])3.0

Hint

Sort a copy, not the caller’s list, then look at the middle pair or single value.

Reference solution in Python
def median_of(values: list[int]) -> float:
    xs = sorted(values)
    n = len(xs)
    if n == 0:
        return 0.0
    mid = n // 2
    return float(xs[mid]) if n % 2 == 1 else (xs[mid - 1] + xs[mid]) / 2

The same problem in another language

More patterns problems in Python