-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmafqueue.py
30 lines (28 loc) · 883 Bytes
/
mafqueue.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
import heapq
class Mqueue:
def __init__(self):
self.heap = []
def enqueue(self, item):
heapq.heappush(self.heap, item)
def __iter__(self):
return MqueueIter(self)
def __bool__(self):
return bool(self.heap)
def __str__(self):
return ("queue with %s items: %s" % (len(self.heap), self.heap))
def __add__(self, other):
return heapq.merge(self.heap, other.heap)
def __len__(self):
return len(self.heap)
def merge(self, other):
self.heap = list(heapq.merge(self.heap, other.heap))
def pop(self):
return heapq.heappop(self.heap)
# have to make a copy since heappop is destructive
class MqueueIter:
def __init__(self, q):
self.heap = list(q.heap)
def __next__(self):
while self.heap:
return heapq.heappop(self.heap)
raise StopIteration