[Getting started with algorithms and data structures] [Day6] A stupid way to use queues to find moving averages

Moving average in Day6 queue

Given an integer data stream and a window size, calculate the moving average of all integers based on the size of the sliding window
Insert picture description here

Queue. The queue module in Python encapsulates the stack and queue. You can directly call the properties and methods of the class. The queue is similar to a pipeline. The elements are first-in, first-out, enter put (arg), and get (). It should be noted that the queue is operated in memory, the process exits, and the queue is emptied. In addition, the queue is also a blocking form.

Type of queue

There are many kinds of queues, but all rely on the module queue
Insert picture description here

Queue method

Insert picture description here

import queue
# 初始化一个大小为3的队列
q = queue.Queue(3)
# 判断队列是否为空
print(q.empty())
# 入队,在队列尾增加数据,block和timeout参数可省略,block为True表示队列已经满了,
# 则阻塞,timeout表示超时间,如果阻塞时间超过了则会报错
q.put(5,block = True,timeout = 5)
# 判断队列是否满了
print(q.full())
# 获取队列当前数据的个数
print(q.qsize())
# 从队列中取出一个元素
print(q.get())

Insert picture description here
Method 1:

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)

Insert picture description here
Method 2:

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))

Insert picture description here
For more details about queues, see
Double-ended queues and circular queues.

Published 42 original articles · praised 28 · visits 4961

Guess you like

Origin blog.csdn.net/KaelCui/article/details/105388241