常用的就是下面4种
注意上面最后一种写错了,应该是collections.deque,deque是在collections包里面的.
求队列元素平均数: 法一:class MovingAverage:
def __init__(self, size: int):
self.size = size
self.queue = []
def next(self, val: int) -> float:
size, queue = self.size, self.queue
queue.append(val)
# calculate the sum of the moving window
window_sum = sum(queue[-size:])
if len(queue) == 1:
return print(queue[0])
else:
tail = " + ".join([str(i) for i in queue[-size:]])
return print("({})/{}={}".format(tail,min(len(queue),size),window_sum / min(len(queue), size)))
m = MovingAverage(3)
m.next(1)
m.next(10)
m.next(5)
m.next(6)
法二:
import queue
class MovingAverage:
def __init__(self,size:int):
self.que = queue.Queue(size)
def next(self,val:int) -> float:
if(self.que.full()):
self.que.get()
self.que.put(val)
return sum(self.que.queue)/self.que.qsize()
m = MovingAverage(3)
print(m.next(1))
print(m.next(10))
print(m.next(5))
print(m.next(6))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)