zoukankan      html  css  js  c++  java
  • (Python基础教程之十九)Python优先级队列示例

    1.什么是优先队列

    • 优先级队列是一种抽象数据类型,类似于常规队列或堆栈数据结构,但每个元素还具有与之关联的“优先级”。
    • 在优先级队列中,优先级高的元素先于优先级低的元素提供。
    • 如果两个元素具有相同的优先级,则将根据其在队列中的顺序为其提供服务。

    2. Python中的优先级队列实现

    以下python程序使用该heapq模块实现简单的优先级队列:

    PriorityQueue.py
    
    import heapq
    
    class PriorityQueue:
    	def __init__(self):
    		self._queue = []
    		self._index = 0
    
    	def push(self, item, priority):
    		heapq.heappush(self._queue, (-priority, self._index, item))
    		self._index += 1
    
    	def pop(self):
    		return heapq.heappop(self._queue)[-1]
    

    3. Python优先级队列示例

    让我们看一个如何使用上面创建的优先级队列的例子。

    example.py
    
    class Item:
    	def __init__(self, name):
    		self.name = name
    
    	def __repr__(self):
    		return 'Item({!r})'.format(self.name)
    
    >>> q = PriorityQueue()
    
    >>> q.push(Item('how'), 1)
    
    >>> q.push(Item('to'), 5)
    
    >>&
  • 相关阅读:
    vue watch 深度监控
    淘宝后台添加颜色尺码动态sku
    js下载
    vue创建1.0项目
    vue assetsPublicPath
    ajax 请求 get请求成功,post 404 not found
    vuejs npm chromedriver 报错
    webpack 输出多个文件
    移动端 js 实现图片上传 预览
    有用的网址
  • 原文地址:https://www.cnblogs.com/daichangya/p/12958391.html
Copyright © 2011-2022 走看看