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)
>>> q.push(Item('do'), 4)
>>> q.push(Item('in'), 2)
>>> q.push(Item('java'), 1)
>>> q.pop()
Item('to') #5
>>> q.pop()
Item('do') #4
>>> q.pop()
Item('in') #2
>>> q.pop()
Item('how') #1
>>> q.pop()
Item('java') #1
关于Python技术储备
学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!
一、Python的学习大礼包
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(文末获取!)
祝:学习愉快、工作顺利
温馨提示:获取方式 关注【码农园区】 回复 “ python ” !!!