Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Moving Average for Time Series

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Moving Average for Time Series. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Castleton Commodities International uses rolling statistics to monitor market time series. Given a sequence of numeric observations and a window size, return the moving average at every position.

For position i, average the values from max(0, i - window + 1) through i. Initial positions use the values available so far, so the output has the same length as the input. Return an empty list when the input series is empty.

Formal Specification

Implement moving_average(values, window).

  • Input: values, a list of integers or floating-point numbers, and window, a positive integer.
  • Output: A list of floating-point averages, with one result for each input value.
  • The function must not modify values.

Constraints

  • 0 <= len(values) <= 10^5
  • 1 <= window <= len(values) when values is non-empty
  • -10^9 <= values[i] <= 10^9
  • The input list must not be modified

Function Signature

def moving_average(values, window):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output