操作

  • 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. PyTorch官方中文文档:torch.Tensor

    torch.Tensor torch.Tensor是一种包含单一数据类型元素的多维矩阵. Torch定义了七种CPU tensor类型和八种GPU tensor类型: Data tyoe CPU te ...

  2. css导航条等元素位置不变

    在容器元素中插入 position: fixed; 如果是在微信小程序中,直接用bottom或者top等就可以简单的设置导航条了.

  3. Nginx 配置对流量、连接和请求的限制

    首先给出配置段: http { limit_conn_zone $binary_remote_addr zone=one:10m; limit_req_zone $binary_remote_addr ...

  4. El表达式的判断字符串的长度和截取,日期时间的格式化

    <c:if test="${fn:length(each.wii_name) >= 20}"> ${fn:substring(each.wii_name, 0,2 ...

  5. MinGW安装和使用

    P.S.安装MinGW主要是code blocks 编译出现了这个问题: ERROR: You need to specify a debugger program in the debuggers' ...

  6. Bootstrap 在手机页时,导航下拉自动回收

    $(".menu-main").collapse("hide"); //.menu-main就是下来导航的类名

  7. AJAX跨域问题解决方法(2)——JSONP解决跨域

    JSONP是什么?JSON全称为JSON with Padding,是JSON的一种补充的使用方式,不是官方协议. 使用JSONP服务器后台要改动吗?JSONP不同于一般的ajax请求返回json对象 ...

  8. MSIL实用指南-创建字段

    本篇讲解怎么创建字段,主要是在修饰符的创建上. 创建字段的方法是TypeBuilder.DefineField,传入字段名称.字段类型.字段修饰符等参数,返回一个FieldBuilder对象.先看这一 ...

  9. 5分钟学习spark streaming之 轻松在浏览器运行和修改Word Counts

    方案一:根据官方实例,下载预编译好的版本,执行以下步骤: nc -lk 9999 作为实时数据源 ./bin/run-example org.apache.spark.examples.sql.str ...

  10. nodejs中的require,exports使用说明

    模块是一门语言编写大项目的基石,因此,了解如何组织.编写.编译.加载模块很重要.这里主要谈谈Node中的模块加载. 1.Node中的模块,主要使用require来加载模块,文件 require(&qu ...