Search code examples
pythonloopsfor-loopappendaverage

Calculate the running mean of the sequence passed in, returns a sequence of same length with the averages


How do I solve this? If the input is [1, 2, 3] the output should be [1, 1.5, 2]. The 1 in the output is the average of the first element from the input. 1.5 from the output is the average of 1, 2. 2 from the output is the average of 1, 2, 3.

I tried to write this:

def running_mean(sequence):
    return sum(sequence)/len(sequence)

But then I only recieve the total average, 2.

Tried with for loop and append. But not sure how to write it.


Solution

  • Step 1 - create partial arrays from initial elements of the array up to given index - in this case:

    [1]
    [1, 2]
    [1, 2, 3]
    

    Step 2 - calculate average of each such partial array with sum(x)/len(x)

    inp = [1, 2, 3]
    
    def running_mean(inp):
        return [sum(x)/len(x) for x in (inp[:i+1] for i in range(0, len(inp)))]
    
    print(running_mean(inp)) # [1.0, 1.5, 2.0]