forked from Sorrop/py-graph-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityQueue.py
More file actions
56 lines (44 loc) · 1.86 KB
/
priorityQueue.py
File metadata and controls
56 lines (44 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import heapq
import itertools
class PriorityQueue:
"""
Collection of items with priorities, such that items can be
efficiently retrieved in order of their priority, and removed. The
items must be hashable.
"""
_REMOVED = object() # placeholder for a removed entry
def __init__(self, iterable=()):
"""Construct a priority queue from the iterable, whose elements are
pairs (item, priority) where the items are hashable and the
priorities are orderable.
"""
self._entry_finder = {} # mapping of items to entries
# Iterable generating unique sequence numbers that are used to
# break ties in case the items are not orderable.
self._counter = itertools.count()
self._data = []
for item, priority in iterable:
self.add(item, priority)
def add(self, item, priority):
"""Add item to the queue with the given priority. If item is already
present in the queue then its priority is updated.
"""
if item in self._entry_finder:
self.remove(item)
entry = [priority, next(self._counter), item]
self._entry_finder[item] = entry
heapq.heappush(self._data, entry)
def remove(self, item):
"""Remove item from the queue. Raise KeyError if not found."""
entry = self._entry_finder.pop(item)
entry[-1] = self._REMOVED
def pop(self):
"""Remove the item with the lowest priority from the queue and return
it. Raise KeyError if the queue is empty.
"""
while self._data:
_, _, item = heapq.heappop(self._data)
if item is not self._REMOVED:
del self._entry_finder[item]
return item
raise KeyError('pop from an empty priority queue')