Problem · Easy · 15 min
Moving average
- Easy
- Arrays
- Math
A sensor sends one number each second. To smooth the numbers, you want the average of every group of size neighbouring numbers.
Write moving_average(values, size). It returns a list. The first item is the average of the first size numbers. The second item is the average of the numbers from position 1 to position size. And so on.
- The result has
len(values) - size + 1items. - If
sizeis less than 1, or larger than the number of values, raise aValueError. - Averages can have decimals. The tests accept a small rounding difference (0.0001).
Examples
| Call | Result |
|---|---|
moving_average([1, 2, 3, 4, 5], 2) |
[1.5, 2.5, 3.5, 4.5] |
moving_average([10, 20, 30], 3) |
[20] |
moving_average([1, 2, 3], 0) |
raises an error |
Tasks
2 to do
Task 1, not checked yet. Make
moving_averagepass the example tests.Task 2, not checked yet. Make
moving_averagepass the hidden tests.
Task 1 of 2
Make moving_average pass the example tests.