Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions maths/moving_average.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import List

Check failure on line 1 in maths/moving_average.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

maths/moving_average.py:1:1: UP035 `typing.List` is deprecated, use `list` instead


def moving_average(values: List[float], window: int) -> List[float]:

Check failure on line 4 in maths/moving_average.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

maths/moving_average.py:4:57: UP006 Use `list` instead of `List` for type annotation

Check failure on line 4 in maths/moving_average.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

maths/moving_average.py:4:28: UP006 Use `list` instead of `List` for type annotation
"""
Compute the moving average of a list of numbers with a given window size.

>>> moving_average([1, 2, 3, 4, 5], 2)
[1.5, 2.5, 3.5, 4.5]
>>> moving_average([10, 20, 30], 3)
[20.0]
>>> moving_average([1, 2], 3)
Traceback (most recent call last):
...
ValueError: Window size cannot be larger than list length.
"""
if window > len(values):
raise ValueError("Window size cannot be larger than list length.")
return [
sum(values[i : i + window]) / window for i in range(len(values) - window + 1)
]
Loading