mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
👾
This commit is contained in:
parent
1d44d182e2
commit
a85ed914d3
320 changed files with 0 additions and 0 deletions
29
queues/moving_average.py
Normal file
29
queues/moving_average.py
Normal file
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
'''
|
||||
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