-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPriorityQueue.py
44 lines (33 loc) · 1.27 KB
/
PriorityQueue.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
# Wrapper class implementing a priority queue interface
# using a Python list as the base data structure and
# algorithms provided by Python's heapq package.
# Not a complete implementation of a priority queue.
# Implements a sufficiently functional priority queue for
# our purposes in Dijkstra's algorithm.
from heapq import heappush, heappop
class PriorityQueue:
def __init__(self, other=None):
self._data = []
if other:
self.extend(other)
def __lt__(self, other):
return not self.isEmpty() and (self.peekWeight() < other.peekWeight() if not other.isEmpty() else False)
def push(self, weight, value):
heappush(self._data, (weight, value))
def pop(self):
return heappop(self._data)[1]
def isEmpty(self):
return len(self._data) == 0
def peek(self):
return self._data[0][1]
def peekWeight(self):
return self._data[0][0]
def extend(self, list):
for elem in list:
heappush(self._data, elem)
# Extend the Priority Queue with the contents
# provided by a passed iterator. Eliminates the need to
# create a list of elements from a graph to add to the queue.
def extendIter(self, iter):
for elem in iter:
heappush(self._data, elem)