-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriority_queue_base.py
52 lines (40 loc) · 1.59 KB
/
priority_queue_base.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
'''
Based on priority_queue_base.py from:
Data Structures and Algorithms in Python
Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
John Wiley & Sons, 2013
'''
from exceptions import Empty
class PriorityQueueBase:
"""Abstract base class for a priority queue."""
#------------------------------ nested _Item class ------------------------------
class _Item:
"""Lightweight composite to store priority queue items."""
__slots__ = '_key', '_value'
def __init__(self, k, v):
self._key = k
self._value = v
def __lt__(self, other):
return self._key < other._key # compare items based on their keys
def __repr__(self):
return '({0},{1})'.format(self._key, self._value)
#------------------------------ public behaviors ------------------------------
def is_empty(self): # concrete method assuming abstract len
"""Return True if the priority queue is empty."""
return len(self) == 0
def __len__(self):
"""Return the number of items in the priority queue."""
raise NotImplementedError('must be implemented by subclass')
def add(self, key, value):
"""Add a key-value pair."""
raise NotImplementedError('must be implemented by subclass')
def min(self):
"""Return but do not remove (k,v) tuple with minimum key.
Raise Empty exception if empty.
"""
raise NotImplementedError('must be implemented by subclass')
def remove_min(self):
"""Remove and return (k,v) tuple with minimum key.
Raise Empty exception if empty.
"""
raise NotImplementedError('must be implemented by subclass')