mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 14:56:27 -04:00
Add files via upload
This commit is contained in:
parent
132a5700c4
commit
8a30000724
3 changed files with 247 additions and 0 deletions
25
stacks_and_queues/moving_average.py
Normal file
25
stacks_and_queues/moving_average.py
Normal file
|
@ -0,0 +1,25 @@
|
|||
'''
|
||||
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.
|
||||
'''
|
||||
|
||||
class MovingAverage:
|
||||
|
||||
def __init__(self, size: int):
|
||||
self.queue = []
|
||||
self.size = size
|
||||
|
||||
|
||||
def next(self, val: int) -> float:
|
||||
|
||||
self.queue.append(val)
|
||||
|
||||
if len(self.queue) > self.size:
|
||||
self.queue.pop(0)
|
||||
|
||||
return sum(self.queue) / len(self.queue)
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue