Skip to content
DeepForgeby svx
All problems
EasyTime Seriests-318

Linearly Weighted Moving Average

Problem

Compute a linearly weighted moving average for every full window of size k, giving the oldest value in a window weight 1 and the newest weight k. Each window average is the dot product of the window with the weights 1, 2, ..., k divided by k * (k + 1) / 2.

Return an empty list when k is not positive or when k exceeds the series length.

Hint

Newer observations carry more weight, so the average lags the raw series less than an SMA.

Test cases

case 1
in: [[1,2,3],2]
expected: [1.6666666666666667,2.6666666666666665]
case 2
in: [[1,2,3],3]
expected: [2.3333333333333335]
case 3
in: [[5],1]
expected: [5]
case 4
in: [[1,2],3]
expected: []
Starter codePython
def linearly_weighted_average(series, k):
    # Your code here
    pass

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