📜  在Python中使用 Queue 和 Heapdict 模块的优先级队列

📅  最后修改于: 2022-05-13 01:55:07.547000             🧑  作者: Mango

在Python中使用 Queue 和 Heapdict 模块的优先级队列

Priority Queue 是队列的扩展,具有以下属性。

  • 具有高优先级的元素在具有低优先级的元素之前出列。
  • 如果两个元素具有相同的优先级,则根据它们在队列中的顺序提供服务。

queue.PriorityQueue(maxsize)

它是优先级队列的构造函数。 maxsize 是可以插入队列的元素个数,默认值为 0。如果 maxsize 值小于或等于 0,则队列大小是无限的。检索项目的优先顺序(最低优先)。
职能-

  • put() –将一个项目放入队列。
  • get() –从队列中移除并返回一个项目。
  • qsize() –返回当前队列大小。
  • empty() –如果队列为空,则返回 True,否则返回 False。它相当于 qsize()==0。
  • full() –如果队列已满,则返回 True,否则返回 False。它等价于 qsize()>=maxsize。

注意: empty()full()qsize()不可靠,因为它们有可能导致队列大小发生变化的竞争条件。

例子:

from queue import PriorityQueue
  
q = PriorityQueue()
  
# insert into queue
q.put((2, 'g'))
q.put((3, 'e'))
q.put((4, 'k'))
q.put((5, 's'))
q.put((1, 'e'))
  
# remove and return 
# lowest priority item
print(q.get())
print(q.get())
  
# check queue size
print('Items in queue :', q.qsize())
  
# check if queue is empty
print('Is queue empty :', q.empty())
  
# check if queue is full
print('Is queue full :', q.full())

输出 :

(1, 'e')
(2, 'g')
Items in queue : 3
Is queue empty : False
Is queue full : False

heapdict()

Heapdict 实现了 MutableMapping ABC,这意味着它的工作方式非常类似于普通的Python字典。它旨在用作优先级队列。除了普通dict()提供的函数外,它还具有popitem()peekitem()函数,它们返回具有最低优先级的对。与 heapq 模块不同,HeapDict 支持有效地更改现有对象的优先级(“减少键”)。更改优先级对于 Dijkstra 算法和 A* 等许多算法很重要。

职能-

  • clear(self) – D.clear() -> 无。从 D 中删除所有项目。
  • peekitem(self) - D.peekitem() -> (k, v),返回值最低的 (key, value) 对;但如果 D 为空,则引发 KeyError。
  • popitem(self) - D.popitem() -> (k, v),移除并返回值最低的 (key, value) 对;但如果 D 为空,则引发 KeyError。
  • get(self, key, default=None ) – D.get(k[, d]) -> D[k] if k in D, else d. d 默认为无。
  • items(self) – D.items() -> 一个类似集合的对象,提供 D 的项目视图
  • keys(self) – D.keys() -> 一个类似集合的对象,提供 D 键的视图
  • values(self) – D.values() -> 一个提供 D 值视图的对象

例子:

import heapdict
  
h = heapdict.heapdict()
  
# Adding pairs into heapdict
h['g']= 2
h['e']= 1
h['k']= 3
h['s']= 4
  
print('list of key:value pairs in h:\n', 
      list(h.items()))
print('pair with lowest priority:\n',
      h.peekitem())
print('list of keys in h:\n',
      list(h.keys()))
print('list of values in h:\n',
      list(h.values()))
print('remove pair with lowest priority:\n',
      h.popitem())
print('get value for key 5 in h:\n',
      h.get(5, 'Not found'))
  
# clear heapdict h
h.clear()
print(list(h.items()))

输出 :

list of key:value pairs in h:
 [('g', 2), ('e', 1), ('k', 3), ('s', 4)]
pair with lowest priority:
 ('e', 1)
list of keys in h:
 ['g', 'e', 'k', 's']
list of values in h:
 [2, 1, 3, 4]
remove pair with lowest priority:
 ('e', 1)
get value for key 5 in h:
 Not found
[]