- Notifications
You must be signed in to change notification settings - Fork 306
/
Copy pathmovingAverage.py
31 lines (25 loc) · 871 Bytes
/
movingAverage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Yu Zhou
# ****************
# Descrption:
# 346. Moving Average from Data Stream
#Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
# ****************
# 思路:
# 没什么难度,基础的stack知识,当size超过self.size的时候,pop掉第一个进入queue的,再加上新的就行了
# 若没超过size,就继续push
# ****************
# Final Solution *
# ****************
classMovingAverage(object):
def__init__(self, size):
self.size=size
self.queue= []
defnext(self, val):
ifnotself.queueorlen(self.queue) <self.size:
self.queue.append(val)
else:
self.queue.pop(0)
self.queue.append(val)
returnfloat(sum(self.queue)) /len(self.queue)