操作

  • Queue() 创建一个空的队列
  • enqueue(item) 往队列中添加一个item元素
  • dequeue() 从队列头部删除一个元素
  • is_empty() 判断一个队列是否为空
  • size() 返回队列的大小
class Queue(object):
"""队列"""
def __init__(self):
self.items = [] def is_empty(self):
return self.items == [] def enqueue(self, item):
"""进队列"""
self.items.insert(0,item) def dequeue(self):
"""出队列"""
return self.items.pop() def size(self):
"""返回大小"""
return len(self.items) if __name__ == "__main__":
q = Queue()
q.enqueue("hello")
q.enqueue("world")
q.enqueue("itcast")
print q.size()
print q.dequeue()
print q.dequeue()
print q.dequeue()

烫手山芋

from pythonds.basic.queue import Queue

def hotPotato(namelist, num):
simqueue = Queue()
for name in namelist:
simqueue.enqueue(name) while simqueue.size() > 1:
for i in range(num):
simqueue.enqueue(simqueue.dequeue()) simqueue.dequeue() return simqueue.dequeue() print(hotPotato(["Bill","David","Susan","Jane","Kent","Brad"],7))

模拟:打印机

主要模拟步骤

  1. 创建打印任务的队列,每个任务都有个时间戳。队列启动的时候为空。
  2. 每秒(currentSecond):

    • 是否创建新的打印任务?如果是,将 currentSecond 作为时间戳添加到队列。
    • 如果打印机不忙并且有任务在等待
      • 从打印机队列中删除一个任务并将其分配给打印机
      • 从 currentSecond 中减去时间戳,以计算该任务的等待时间。
      • 将该任务的等待时间附件到列表中稍后处理。
      • 根据打印任务的页数,确定需要多少时间。
    • 打印机需要一秒打印,所以得从该任务的所需的等待时间减去一秒。
    • 如果任务已经完成,换句话说,所需的时间已经达到零,打印机空闲。
  3. 模拟完成后,从生成的等待时间列表中计算平均等待时间。
# 模拟打印机
class Printer:
def __init__(self, ppm):
self.pagerate = ppm
self.currentTask = None
self.timeRemaining = 0 def tick(self):
if self.currentTask != None:
self.timeRemaining = self.timeRemaining - 1
if self.timeRemaining <= 0:
self.currentTask = None def busy(self):
if self.currentTask != None:
return True
else:
return False def startNext(self,newtask):
self.currentTask = newtask
self.timeRemaining = newtask.getPages() * 60/self.pagerate # 模拟任务
import random class Task:
def __init__(self,time):
self.timestamp = time
self.pages = random.randrange(1,21) def getStamp(self):
return self.timestamp def getPages(self):
return self.pages def waitTime(self, currenttime):
return currenttime - self.timestamp #模拟打印机任务队列
from pythonds.basic.queue import Queue import random def simulation(numSeconds, pagesPerMinute): labprinter = Printer(pagesPerMinute)
printQueue = Queue()
waitingtimes = [] for currentSecond in range(numSeconds): if newPrintTask():
task = Task(currentSecond)
printQueue.enqueue(task) if (not labprinter.busy()) and (not printQueue.isEmpty()):
nexttask = printQueue.dequeue()
waitingtimes.append(nexttask.waitTime(currentSecond))
labprinter.startNext(nexttask) labprinter.tick() averageWait=sum(waitingtimes)/len(waitingtimes)
print("Average Wait %6.2f secs %3d tasks remaining."%(averageWait,printQueue.size())) def newPrintTask():
num = random.randrange(1,181)
if num == 180:
return True
else:
return False for i in range(10):
simulation(3600,5)

Python 实现队列的更多相关文章

  1. python消息队列snakemq使用总结

    Python 消息队列snakemq总结 最近学习消息总线zeromq,在网上搜了python实现的消息总线模块,意外发现有个消息队列snakemq,于是拿来研究一下,感觉还是很不错的,入手简单使用也 ...

  2. python RabbitMQ队列使用(入门篇)

    ---恢复内容开始--- python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种que ...

  3. Python之队列Queue

    今天我们来了解一下python的队列(Queue) queue is especiall useful in threaded programming when information must be ...

  4. Python消息队列工具 Python-rq 中文教程

    原创文章,作者:Damon付,如若转载,请注明出处:<Python消息队列工具 Python-rq 中文教程>http://www.tiangr.com/python-xiao-xi-du ...

  5. Python 用队列实现多线程并发

    # Python queue队列,实现并发,在网站多线程推荐最后也一个例子,比这货简单,但是不够规范 # encoding: utf-8 __author__ = 'yeayee.com' # 由本站 ...

  6. python RabbitMQ队列使用

    python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种queue都是只能在同一个进程下 ...

  7. Python之队列

    Python之队列 队列:先进先出 队列与线程有关. 在多线程编程时,会起到作用. 作用:确保信息安全的进行交换. 有get 和 put 方法. ''' 创建一个“队列”对象 import Queue ...

  8. Python 单向队列Queue模块详解

    Python 单向队列Queue模块详解 单向队列Queue,先进先出 '''A multi-producer, multi-consumer queue.''' try: import thread ...

  9. Python 双向队列Deque、单向队列Queue 模块使用详解

    Python 双向队列Deque 模块使用详解 创建双向队列Deque序列 双向队列Deque提供了类似list的操作方法: #!/usr/bin/python3 import collections ...

  10. python 线程队列PriorityQueue(优先队列)(37)

    在 线程队列Queue / 线程队列LifoQueue 文章中分别介绍了先进先出队列Queue和先进后出队列LifoQueue,而今天给大家介绍的是最后一种:优先队列PriorityQueue,对队列 ...

随机推荐

  1. C#图解教程 第二十四章 反射和特性

    反射和特性 元数据和反射Type 类获取Type对象什么是特性应用特性预定义的保留的特性 Obsolete(废弃)特性Conditional特性调用者信息特性DebuggerStepThrough 特 ...

  2. CentOS7使用dnf安装mysql

    1.安装mysql的yum仓库 执行以下命令: yum localinstall https://dev.mysql.com/get/mysql57-community-release-el7-11. ...

  3. 备库搭建后,进入备库报错psql: FATAL: the database system is starting up

        备库搭建后,进入备库报错psql: FATAL:  the database system is starting up  原因:备库配置文件没有hot_standby = on   mast ...

  4. 画一个DIV并给它的四个角变成圆形,且加上阴影

    <!doctype html><html><head><meta charset="utf-8"><title>无标题文 ...

  5. C++学习-8

    1.注意:函数指针前面*,&都是一样的没啥实际意义,除了把实例化函数块的时候,需要指针或者引用修饰    cout << typeid(my1.show).name() <& ...

  6. Redis 桌面管理器

    使用Redis桌面管理器,可以方便开发人员进行开发测试,对Redis存储内容进行可视化管理. 下载安装:https://redisdesktop.com/download 1. 为了方便测试,打开re ...

  7. Node与apidoc的邂逅——NodeJS Restful 的API文档生成

    作为后台根据需求文档开发完成接口后,交付给前台(angular vue等)做开发,不可能让前台每个接口调用都去查看你的后台代码一点点查找.前台开发若不懂你的代码呢?让他一个接口一个接口去问你怎么调用, ...

  8. SpringBoot就是这么简单

    一.SpringBoot入门 今天在慕课网中看见了Spring Boot这么一个教程,这个Spring Boot作为JavaWeb的学习者肯定至少会听过,但我是不知道他是什么玩意. 只是大概了解过他是 ...

  9. python笔记之异常

    异常 內建异常在exceptions模块内,使用dir函数列出模块的内容. 自定义异常类:继承基类Exception. 异常可以使用raise语句引发,可以使用try ... except ... e ...

  10. Git - 可视化冲突解决工具P4Merge

    P4Merge P4Merge是Git的一个第三发Diff和Merge工具(可视化冲突解决工具). 下载地址: https://www.perforce.com/downloads/visual-me ...