操作

  • 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. 【CF245H】Queries for Number of Palindromes(回文树)

    [CF245H]Queries for Number of Palindromes(回文树) 题面 洛谷 题解 回文树,很类似原来一道后缀自动机的题目 后缀自动机那道题 看到\(n\)的范围很小,但是 ...

  2. 【NOIP2016】【CJOJ2257】2257 愤怒的小鸟

    题目 Description https://www.luogu.org/problem/show?pid=2831 Kiana最近沉迷于一款神奇的游戏无法自拔. 简单来说,这款游戏是在一个平面上进行 ...

  3. [BZOJ2326] [HNOI2011] 数学作业 (矩阵乘法)

    Description Input Output Sample Input Sample Output HINT Source Solution 递推式长这样:$f[n]=f[n-1]*10^k+n$ ...

  4. 【MyBatis源码分析】插件实现原理

    MyBatis插件原理----从<plugins>解析开始 本文分析一下MyBatis的插件实现原理,在此之前,如果对MyBatis插件不是很熟悉的朋友,可参看此文MyBatis7:MyB ...

  5. 【经验随笔】Java通过代理访问互联网平台提供的WebService接口的一种方法

    背景 通常有两点原因需要通过代理访问互联网平台的提供的WebService接口: 1. 在公司企业内网访问外部互联网平台发布的接口,公司要求通过代理访问外网. 2. 频繁访问平台接口,IP被平台封了, ...

  6. 误操作导致 lvdisplay 命令不存在解决

    1.lvdisplay 命令不存在 查看lvm2 包被卸载2.执行 yum install lvm2 命令 发现 yum 被锁 3.删除yum.lock 发现/ 目录只读4.mount -o remo ...

  7. Android Services (后台服务)

    一.简介 服务是可以在后台执行长时间运行的应用程序组件,它不提供用户界面. 另一个应用程序组件可以启动一个服务,并且即使用户切换到另一个应用程序,它仍然在后台运行. 另外,组件可以绑定到一个服务来与它 ...

  8. C++学习-5

    1.static_cast静态转换<>要转换的类型,不适用于指针转换 reinterpret_cast<char*>()指针类型的转换 涉及到const,必须用const_ca ...

  9. java 开发 face++ 人脸特征识别系统

    首先要在 face++ 注册一个账号,并且创建一个应用,拿到 api key 和 api secret: 下载 java 接入工具,一个 jar 包:https://github.com/FacePl ...

  10. jQuery中的ajax的相关方法

    JQuery对Ajax操作进行了封装,$.ajax()方法属于最底层的方法,第2层是load().$.get().$.post()方法,第3层是$.getScript()和$.getJSON()方法. ...