Drill

ProblemsPython › patterns

The average so far, after every reading

easypatternsPrefix sumsArraysMathPython

A quality chart plots not each reading but the average of everything measured up to that point, so a late wobble does not swing the line.

running_average(readings: list<int>) → list<int>

Solve it in the editor →

Where you start

def running_average(readings: list[int]) -> list[int]:
    

Worked examples

CallResult
running_average([10, 20, 30])[10, 15, 20]
running_average([1, 2])[1, 1]
running_average([5])[5]
running_average([])[]

Hint

Carry the running total and divide by how many readings you have seen. Do not re-add the list each step.

Reference solution in Python
def running_average(readings: list[int]) -> list[int]:
    out = []
    total = 0
    for i, reading in enumerate(readings):
        total += reading
        out.append(total // (i + 1))
    return out

The same problem in another language

More patterns problems in Python