Practice

Problem 3 of 10

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 + 1 items.
  • If size is less than 1, or larger than the number of values, raise a ValueError.
  • 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

  1. Task 1, not checked yet. Make moving_average pass the example tests.

  2. Task 2, not checked yet. Make moving_average pass the hidden tests.

Task 1 of 2

Make moving_average pass the example tests.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter runs all the tests. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.