easy +10 pts

Rolling Window Mean

Compute the mean of every contiguous subarray of a given window size.

Write a function `rolling_window_mean(nums, k)` that takes a list of numbers `nums` and an integer `k` (1 <= k <= len(nums)) and returns a list of floats: the arithmetic mean of each contiguous subarray of length `k`, in the order they appear. The means should be rounded to 4 decimal places (e.g., use `round(mean, 4)`).

Constraints

`nums` is a list of integers or floats, with length between 1 and 100,000. `k` is an integer satisfying 1 <= k <= len(nums). Time complexity O(n) is expected. Do not use `statistics` or `numpy`.

Example

>>> rolling_window_mean([1, 2, 3, 4], 2)
[1.5, 2.5, 3.5]
>>> rolling_window_mean([1, 1, 1], 3)
[1.0]
>>> rolling_window_mean([5], 1)
[5.0]
10 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

First compute the sum of the first k elements.
Slide the window by adding the next element and subtracting the one that leaves.
For each window, append the mean rounded to 4 decimals.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.