Python实现优先级队列
基于最大堆实现的优先级队列
class Array(object):
def __init__(self, size=32, init=None):
self._size = size
self._items = [init] * self._size
def __getitem__(self, index):
return self._items[index]
def __setitem__(self, index, value):
self._items[index] = value
def __len__(self):
return self._size
def clear(self, value=None):
for i in range(len(self._items)):
self._items[i] = value
def __iter__(self):
for item in self._items:
yield item
class MaxHeap(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self._elements = Array(maxsize)
self._count = 0
def __len__(self):
return self._count
def add(self, value):
if self._count >= self.maxsize:
raise Exception("full")
# 把值插入最后一位
self._elements[self._count] = value
self._count += 1
# 维持最大堆属性
self._siftup(self._count-1)
def _siftup(self, ndx):
if ndx > 0:
parent = int((ndx-1)/2)
# 如果插入的值大于 parent,一直交换
if self._elements[ndx] > self._elements[parent]:
self._elements[ndx], self._elements[parent] = self._elements[parent], self._elements[ndx]
# 递归交换
self._siftup(parent)
def extract(self):
"""
获取并且移除根节点
:return:
"""
if self._count <= 0:
raise Exception("empty")
# 保存root节点
value = self._elements[0]
self._count -= 1
# 最右下的节点放到root后siftDown
self._elements[0] = self._elements[self._count]
# 维持堆特性
self._siftdown(0)
return value
def _siftdown(self, ndx):
# 下筛选操作
left = 2 * ndx + 1
right = 2 * ndx + 2
# 确定哪个节点包含较大的值
largest = ndx
if (left < self._count and # 有左孩子
self._elements[left] >= self._elements[largest] and # 左孩子的值大于要找的
self._elements[left] >= self._elements[right]): # 左孩子的值大于右孩子的值
# 更新最大的下标为左孩子的下标
largest = left
elif right < self._count and self._elements[right] >= self._elements[largest]:
# 更新最大的下标为右孩子的下标
largest = right
# 不等的话就交换更新 然后递归调用
if largest != ndx:
self._elements[ndx], self._elements[largest] = self._elements[largest], self._elements[ndx]
self._siftdown(largest)
class PriorityQueue(object):
def __init__(self, maxsize):
self.maxsize = maxsize
self._maxheap = MaxHeap(maxsize)
def push(self, priority, value):
# 注意这里把这个 tuple push 进去,python 比较 tuple 从第一个开始比较
# 这样就很巧妙地实现了按照优先级排序
entry = (priority, value) # 入队的时候会根据 priority 维持堆的特性
self._maxheap.add(entry)
def pop(self, with_priority=False):
entry = self._maxheap.extract()
if with_priority:
return entry
else:
return entry[1]
def is_empty(self):
return len(self._maxheap) == 0