-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.py
62 lines (54 loc) · 1.86 KB
/
heap.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from heapq import heappush
from heapq import heappop
import numpy as np
class Heap:
def __init__(self,
random=None):
if not isinstance(random, np.random.RandomState):
random = np.random.RandomState(random)
self._random = random
self._pq = []
self._REMOVED = '<removed-task>'
self._element_finder = {}
self._n = 0
def push(self,
priority,
element,
extra=None):
if element in self._element_finder:
self.remove(element)
tiebreaker = self._random.random()
entry = [priority, tiebreaker, element, extra]
self._element_finder[element] = entry
heappush(self._pq, entry)
self._n += 1
def push_if_better(self,
priority,
element,
extra=None):
if element in self._element_finder:
if self._element_finder[element][0] <= priority:
# The better element is already in the queue. Do nothing
return
else:
self.remove(element)
tiebreaker = self._random.random()
entry = [priority, tiebreaker, element, extra]
self._element_finder[element] = entry
heappush(self._pq, entry)
self._n += 1
def remove(self,
element):
entry = self._element_finder.pop(element)
entry[-2] = self._REMOVED
self._n -= 1
def pop(self):
while len(self._pq) > 0:
priority, _, element, extra = heappop(self._pq)
if element is not self._REMOVED:
del self._element_finder[element]
self._n -= 1
return priority, element, extra
raise KeyError('Tried to pop from an empty priority queue')
def __len__(self):
return self._n