pythonintermediate10 minutes
Create a Function to Calculate Moving Average of a List
Write a Python function that computes the moving average over a specified window size for a list of numerical values.
Challenge prompt
Write a function named moving_average that takes two parameters: a list of numbers and an integer window size n. The function should return a list of the moving averages calculated over the window n across the list. Each moving average is the average of n consecutive elements. If the window size is larger than the list, return an empty list.
Guidance
- • Iterate through the list by slices of length n to compute each window's average.
- • Handle edge cases like an empty list or window size larger than the list length.
- • Consider using list comprehension for a clean and concise solution.
Hints
- • Use slicing: list[i:i+n] to get the current window of elements.
- • Sum the elements in the slice and divide by n to get the average.
- • Think about how many moving averages you will calculate based on the list length and window size.
Starter code
def moving_average(numbers, n):
# Your code here
passExpected output
moving_average([1, 2, 3, 4, 5], 3) -> [2.0, 3.0, 4.0]
Core concepts
list slicingloopsfunctionsaverages
Challenge a Friend
Send this duel to someone else and see if they can solve it.