Files
Python_CookBook_repo/1.数据结构与算法/5.优先级队列.py
2025-09-10 16:12:45 +08:00

43 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import heapq
# 优先级队列(使用小根堆实现)
class PriorityQueue:
def __init__(self):
self._queue = []
# 由于优先级在比较大小时可能相同造成比较失败维护一个下标index来进行二级辨识
self._index = 0
# 由于heapq的原理是生成一个小根堆所以优先级取负这样优先级越大堆识别到的优先级越小引入index在优先级相同时比较入栈先后顺序
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]
# 在Python中实例化对象是不可以直接进行比较的例如
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item {!r}'.format(self.name)
# a = Iter('foo') b = Iter('bar'), 进行a<b比较会输出报错
# 一个优先级队列的简单调用示例
if __name__ == "__main__":
q = PriorityQueue()
q.push(Item("foo"), 1)
q.push(Item("bar"), 5)
q.push(Item("spam"), 4)
q.push(Item("grok"), 1)
a = q.pop()
b = q.pop()
c = q.pop()
d = q.pop()
print(a)