This is what I usually present as a side note in some of my template conversations:
class PriorityQueue(object): def __init__(self, key=lambda x: x): self.l = [] self.key = key def __len__(self): return len(self.l) def push(self, obj): heapq.heappush(self.l, (self.key(obj), obj)) def pop(self): return heapq.heappop(self.l)[-1]
Obviously, OP requirements should use operator.itemgetter('priority') as the key argument when creating the PriorityQueue instance (of course, import operator is required at the top of the module ;-).
Alex martelli
source share