-
Notifications
You must be signed in to change notification settings - Fork 4
/
priority.py
35 lines (29 loc) · 968 Bytes
/
priority.py
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
from heapq import heappush, heappop
class PriorityQueue:
def __init__(self):
self.item_heap = [] # [ [priority, item] ]
self.dummy = '<dummy entry>'
self.item_dict = {} # { item: [priority, item] }
def __bool__(self):
return bool(self.item_dict)
def add(self, item, priority=0):
try:
self.remove(item)
except KeyError:
pass
wrapper = [priority, item]
heappush(self.item_heap, wrapper)
self.item_dict[item] = wrapper
def remove(self, item):
wrapper = self.item_dict[item]
wrapper[1] = self.dummy
def pop(self):
while True:
if not self.item_heap:
raise KeyError('pop from an empty priority queue')
wrapper = heappop(self.item_heap)
item = wrapper[1]
if item is not self.dummy:
break
del self.item_dict[item]
return wrapper[1]