Skip to content
DeepForgeby svx
All problems

Incremental Mean Update

Problem

Update a running mean with one new observation.

Given the mean of n samples and a new value x, return mean + (x - mean) / (n + 1), which is the mean of the n + 1 samples.

Hint

Pull the old mean toward the new value by 1 / (n + 1).

Test cases

case 1
in: [2,3,6]
expected: 3
case 2
in: [0,0,10]
expected: 10
case 3
in: [5,1,1]
expected: 3
case 4
in: [-2,4,3]
expected: -1
Starter codePython
def incremental_mean(mean, n, x):
    # Your code here
    pass

4 test cases · run your code against them in the editor