Running Average Tracker With Nonlocal State

Hard ⏱ 18 min 24% acceptance ★★★★☆ 4.2
Write a function make_running_average() that returns a function add_sample(value). Each call to add_sample should add value to a running total and count (both tracked via nonlocal in the enclosing scope) and return the current average as a float, rounded to 2 decimal places.

Examples

Example 1
Input
avg = make_running_average()
avg(10)
avg(20)
avg(30)
Output
10.0, 15.0, 20.0
Explanation

After each sample the running average updates: 10/1=10.0, 30/2=15.0, 60/3=20.0.

Constraints

  • State must be stored in the enclosing function scope and mutated with nonlocal, not with a global or a mutable default argument.
  • Each call to make_running_average() must start a fresh, independent tracker.

Topics

Functionsnonlocalclosures

Companies

Deutsche BankGoldman Sachs

Hints

Hint 1

Declare total = 0 and count = 0 in the outer function, then use `nonlocal total, count` inside add_sample before modifying them.

Hint 2

Return round(total / count, 2) after updating.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.