Python 实现队列
操作
- 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))
模拟:打印机
主要模拟步骤
- 创建打印任务的队列,每个任务都有个时间戳。队列启动的时候为空。
每秒(currentSecond):
- 是否创建新的打印任务?如果是,将
currentSecond作为时间戳添加到队列。 - 如果打印机不忙并且有任务在等待
- 从打印机队列中删除一个任务并将其分配给打印机
- 从
currentSecond中减去时间戳,以计算该任务的等待时间。 - 将该任务的等待时间附件到列表中稍后处理。
- 根据打印任务的页数,确定需要多少时间。
- 打印机需要一秒打印,所以得从该任务的所需的等待时间减去一秒。
- 如果任务已经完成,换句话说,所需的时间已经达到零,打印机空闲。
- 是否创建新的打印任务?如果是,将
- 模拟完成后,从生成的等待时间列表中计算平均等待时间。
# 模拟打印机
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 实现队列的更多相关文章
- python消息队列snakemq使用总结
Python 消息队列snakemq总结 最近学习消息总线zeromq,在网上搜了python实现的消息总线模块,意外发现有个消息队列snakemq,于是拿来研究一下,感觉还是很不错的,入手简单使用也 ...
- python RabbitMQ队列使用(入门篇)
---恢复内容开始--- python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种que ...
- Python之队列Queue
今天我们来了解一下python的队列(Queue) queue is especiall useful in threaded programming when information must be ...
- Python消息队列工具 Python-rq 中文教程
原创文章,作者:Damon付,如若转载,请注明出处:<Python消息队列工具 Python-rq 中文教程>http://www.tiangr.com/python-xiao-xi-du ...
- Python 用队列实现多线程并发
# Python queue队列,实现并发,在网站多线程推荐最后也一个例子,比这货简单,但是不够规范 # encoding: utf-8 __author__ = 'yeayee.com' # 由本站 ...
- python RabbitMQ队列使用
python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种queue都是只能在同一个进程下 ...
- Python之队列
Python之队列 队列:先进先出 队列与线程有关. 在多线程编程时,会起到作用. 作用:确保信息安全的进行交换. 有get 和 put 方法. ''' 创建一个“队列”对象 import Queue ...
- Python 单向队列Queue模块详解
Python 单向队列Queue模块详解 单向队列Queue,先进先出 '''A multi-producer, multi-consumer queue.''' try: import thread ...
- Python 双向队列Deque、单向队列Queue 模块使用详解
Python 双向队列Deque 模块使用详解 创建双向队列Deque序列 双向队列Deque提供了类似list的操作方法: #!/usr/bin/python3 import collections ...
- python 线程队列PriorityQueue(优先队列)(37)
在 线程队列Queue / 线程队列LifoQueue 文章中分别介绍了先进先出队列Queue和先进后出队列LifoQueue,而今天给大家介绍的是最后一种:优先队列PriorityQueue,对队列 ...
随机推荐
- 【洛谷T7152】(考试题目)细胞
题面 题目描述 小 X 在上完生物课后对细胞的分裂产生了浓厚的兴趣.于是他决定做实验并 观察细胞分裂的规律. 他选取了一种特别的细胞,每天每个该细胞可以分裂出 x − 1 个新的细胞. 小 X 决定第 ...
- java&python环境变量+idea&pycharm激活
java: JAVA_HOME=C:\jdk1.5.0_06 PATH=%JAVA_HOME%\bin;%PATH% CLASSPATH=.;%JAVA_HOME%\lib;%JAVA_HOME%\l ...
- button 和input 的区别及在表单form中的用法
先说一下button 和input的定义: <button> 标签定义的是一个按钮 1.在 <button> 元素内部,您可以放置任何内容,比如文本或图像.这是该元素与使用 & ...
- 夹缝中求生存-在一无所有的php虚拟主机环境下利用smtp发送邮件(二)
夹缝中求生存 前言:在上一篇随笔中,以163个人邮箱作为发送邮箱地址,当收件邮箱为QQ邮箱时,极有可能会被直接扔进邮件垃圾箱里,为了解决这个问题,申请注册企业邮箱,可以减少发出的邮件被当作垃圾邮件的可 ...
- Docker学习——pinpoint部署
Pinpoint Install pinpoint-server 下载镜像 docker pull yous/pinpoint 查看镜像 docker images 启动容器 docker run - ...
- MongoDB起步
1.Mongodb基本概念和SQL的区别:SQL术语 MongoDB术语database databasetable collectionrow doc ...
- Google Chrome Plus——绿色便携多功能谷歌浏览器
我更新浏览器的时候一般没有时间更新这个帖子,所以具体请看我网盘下载链接里面的更新日志,请自行查看最新版本下载,谢谢. 近期更新日期:2016.8.15(此时间可能不是最新,请看我网盘里面的更新日志) ...
- install-scp
centos6 minilize system will not scp command install: yum -y install openssh-clients and another mac ...
- selenium 断言与验证
断言和验证都是判断结果是否跟预期效果是否一致,不一致的情况下,断言会导致测试用例直接失败,程序不会继续执行:验证的测试用例会继续执行. 断言的4种模式+5种手段: assert 断言失败时,该测试将终 ...
- neo智能合约的生命周期