#coding:utf-8
"""
fzh created on 2019/10/15
构建一个队列
"""
import datetimeclass LoopQueue(object):def __init__(self, n=10):self.arr = [None] * (n+1) # 由于特意浪费了一个空间,所以arr的实际大小应该是用户传入的容量+1self.front = 0self.tail = 0self.size = 0def __str__(self):return str(self.arr)def __len__(self):return len(self.arr)def __iter__(self):return iter(self.arr)def get_size(self):# 获取队列元素个数return self.sizedef get_capaticty(self):# 获取队列容积(实际可存储元素个数)return self.__len__() - 1def is_full(self):# 判断队列是否为满return (self.tail+1) % len(self.arr) == self.frontdef is_empty(self):# 判断队列是否为空return self.size == 0def get_front(self):# 获取队首return self.arr[self.front]def enqueue(self, e):# 入队if self.is_full():self.resize(self.get_capaticty() * 2) # 如果队列满,以当前队列容积的2倍进行扩容self.arr[self.tail] = eself.tail = (self.tail+1) % len(self.arr)self.size += 1def dequeue(self):# 出队if self.is_empty():raise Exception("Cannot dequeue from en empty queue")result = self.arr[self.front]self.arr[self.front] = Noneself.front = (self.front+1) % len(self.arr)self.size -= 1# 如果元素个数少于容积的1/4并且元素个数if self.size < self.get_capaticty() // 4 and self.get_capaticty() > 1:self.resize(self.get_capaticty() // 2)return resultdef resize(self, new_capacity):new_arr = [None] * (new_capacity+1)for i in range(self.size):new_arr[i] = self.arr[(i+self.front) % len(self.arr)]self.arr = new_arrself.front = 0self.tail = self.sizedef main(loop_queue,imgs_list_path):start_time = datetime.datetime.now()for i, img_list_path in enumerate(imgs_list_path):loop_queue.enqueue(img_list_path)print('\n---------测试enqueue----------')print('Loop_Queue: size = {0} , capacity = {1}'.format(loop_queue.get_size(), loop_queue.get_capaticty()))print('loop_queue:', loop_queue)# print('is_empty:', loop_queue.is_empty())# print('is_full:', loop_queue.is_full())print('get_front:', loop_queue.get_front())print('=====队列输出结果=====')#算法处理完,更新数据,同时出队for i in range(loop_queue.get_size()):deq_res = loop_queue.dequeue()print('deq_res:', deq_res)#加入算法处理过程last_time = datetime.datetime.now() - start_timeprint('---------测试dequeue----------')print('Loop_Queue: size = {0} , capacity = {1}'.format(loop_queue.get_size(), loop_queue.get_capaticty()),loop_queue)# print('is_empty:', loop_queue.is_empty())# print('is_full:', loop_queue.is_full())print('get_front:', loop_queue.get_front())# #这个是去异步轮询查找数据库,如果没有处理的,加入队列# for i, img_list_path in enumerate(imgs_list_path):# loop_queue.enqueue(img_list_path)# print(loop_queue)
if __name__ == '__main__':imgs_list_path = ['1.jpg', '2.jpg', '3.jpg', '4.jpg']loop_queue = LoopQueue()main(loop_queue,imgs_list_path)