#305 · Working with data · Intermediate · 70 XP · about 14 min
A weather station records one reading a day, and readings[i] is the reading for day i: a whole number, or None on a day the sensor was down.
Write moving_average(readings, k) that returns the k-day moving average as a list: for every day i from day k - 1 to the last day, the average of the readings that exist among the k days ending on day i (days i - k + 1 to i). Each average is a float, the sum of those readings divided by how many there are, rounded with round(average, 2). If none of those k days has a reading, the value for that day is None.
The list has len(readings) - k + 1 values, or none at all when there are fewer than k days.
moving_average([10, 12, 14, 16], 2) # returns [11.0, 13.0, 15.0] moving_average([3, None, 4, None, None, 8], 3) # returns [3.5, 4.0, 4.0, 8.0] moving_average([5, None, None, 2], 2) # returns [5.0, None, 2.0]
In the second example the first window holds 3, None and 4, so its average is (3 + 4) / 2 = 3.5.
0 <= len(readings) <= 100000 and 1 <= k <= 1000None.First solves only, ranked by stars and then time.