Skip to content

Commit 28399f5

Browse files
author
studentpiyush
committed
Add moving average algorithm (math/moving_average.py)
1 parent ef2072a commit 28399f5

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

maths/moving_average.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
def moving_average(values: List[float], window: int) -> List[float]:
4+
"""
5+
Compute the moving average of a list of numbers with a given window size.
6+
7+
>>> moving_average([1, 2, 3, 4, 5], 2)
8+
[1.5, 2.5, 3.5, 4.5]
9+
>>> moving_average([10, 20, 30], 3)
10+
[20.0]
11+
>>> moving_average([1, 2], 3)
12+
Traceback (most recent call last):
13+
...
14+
ValueError: Window size cannot be larger than list length.
15+
"""
16+
if window > len(values):
17+
raise ValueError("Window size cannot be larger than list length.")
18+
return [sum(values[i:i+window]) / window for i in range(len(values)-window+1)]

0 commit comments

Comments
 (0)