""" priorityqueue.py >>> from priorityqueue import PriorityQueue >>> pq = PriorityQueue() >>> pq.push(15) >>> pq.push(10) >>> pq.push(12) >>> pq.pop() 10 >>> pq.pop() 12 >>> pq.pop() 15 >>> pq2 = PriorityQueue([2, 15, 7, 4]) >>> [x+1 for x in pq2] [3, 5, 8, 16] >>> len(pq2) 4 >>> str(pq2) '[2, 4, 7, 15]' >>> pq2[0] 2 >>> pq2[0] = 9 An object wrapper around Python's heapq package (see http://docs.python.org/library/heapq.html). I just didn't like their API. Jim M | MIT License | Feb 21 2012 """ from heapq import heapify, heappush, heappop from doctest import testmod class PriorityQueue(object): def __init__(self, queue=[]): self.heap = queue heapify(self.heap) def push(self, item): heappush(self.heap, item) def pop(self): return heappop(self.heap) def __str__(self): return str(self.heap) def __len__(self): return len(self.heap) def __getitem__(self, key): return self.heap[key] def __setitem__(self, key, value): self.heap[key] = value def __iter__(self): self.popped = [] heapify(self.popped) return self def next(self): if len(self)==0: self.heap = self.popped self.popped = None raise StopIteration else: x = self.pop() heappush(self.popped, x) return x if __name__ == "__main__": testmod()