class SortedPriorityQueue(PriorityQueueBase): """A min-oriented priority queue implemented with a sorted list.""" def __init__(self): """Create a new empty Priority Queue.""" self._data = PositionalList() def __len__(self): """Return the number of items in the priority queue.""" return len(self._data) def add(self, key, value): """Add a key-value pair.""" newest = self._Item(key, value) walk = self._data.last() # walk backward looking for smaller key while walk is not None and newest < walk.element(): walk = self._data.before(walk) if walk is None: self._data.add_first(newest) # new key is the smallest else: self._data.add_after(walk, newest) # newest goes after walk def min(self): """Return but do not remove (k, v) tuple with minimum key.""" if self.is_empty(): raise Empty('Priority queue is empty.') p = self._data.first() item = p.element() return (item._key, item._value) def remove_min(self): """Remove and return (k, v) tuple with minimum key from the priority queue.""" if self.is_empty(): raise Empty('Priority queue is empty.') item = self._data.delete(self._data.first()) return (item._key, item._value)
def test_add_after_inserts_element_after_given_Position_and_returns_Position( self): pl = PositionalList() n = PositionalList._Node('foo', pl._header, pl._trailer) pl._header._next = n pl._trailer._prev = n existing_position = PositionalList.Position(pl, n) element = 'foo' result_position = pl.add_after(existing_position, element) self.assertIs(result_position._node._element, element) self.assertIs(result_position._node._prev, existing_position._node) self.assertIs(result_position._node._next, pl._trailer) self.assertIs(existing_position._node._next, result_position._node)