[Problem] Moving Average from Data Stream

댕청·2025년 6월 18일

문제 풀이

목록 보기
11/38

Description

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Implement the MovingAverage class:

MovingAverage(int size) Initializes the object with the size of the window size.
double next(int val) Returns the moving average of the last size values of the stream.

Example

Input
["MovingAverage", "next", "next", "next", "next"]

[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]

Explanation

MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3

Approach

Foremost, I would like to acknowledge how terribly this problem is phrased. To restate the problem, we are only asked to create the class movingaverage, which allows to initiate a queue with a maximum size, and the function next continues to insert values inside the queue, returning the average value. If the queue exceeds the maximum value, it removes the value that has been inserted at the beginning (FIFO - first in first out).

Solution

The solution itself is a simple queue problem, where I used the collections library to create queues.

import collections
class MovingAverage(object):

    def __init__(self, size):
        self.size = size
        self.queue = collections.deque()
        self.total = 0

    def next(self, val):
        if len(self.queue) == self.size:
            self.total -= self.queue.popleft()
        self.queue.append(val)
        self.total += val    
        return float(self.total) / len(self.queue)
profile
될때까지 모든 걸 다시 한번

0개의 댓글