In [1]:
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
In [2]:
# Example use
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)
q = PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('bar'), 5)
q.push(Item('spam'), 4)
q.push(Item('grok'), 1)
In [3]:
print("Should be bar:", q.pop())
print("Should be spam:", q.pop())
print("Should be foo:", q.pop())
print("Should be grok:", q.pop())
In [5]:
a = (1, Item('foo'))
b = (5, Item('bar'))
a < b
Out[5]:
In [6]:
c = (1, Item('grok'))
a < c
(priority, index, item)
tuples, you avoid this problem entirely since no two tuples will ever have the same value for index
In [8]:
a = (1, 0, Item('foo'))
b = (5, 1, Item('bar'))
c = (1, 2, Item('grok'))
a < b # True
Out[8]:
In [9]:
a < c # True
Out[9]: