(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)
>>&
        
        如果你喜欢本文, 请长按二维码,关注公众号 分布式编程.
        
        作者:分布式编程
        
        出处:https://zthinker.com/
        
        本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    
 
                     
                    
                 
                    
                 
                
            
         
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号