Skip to content

Instantly share code, notes, and snippets.

@cppio
Created December 29, 2019 23:23
Show Gist options
  • Select an option

  • Save cppio/2a8d101bd601f25c0bf15ca741618cc5 to your computer and use it in GitHub Desktop.

Select an option

Save cppio/2a8d101bd601f25c0bf15ca741618cc5 to your computer and use it in GitHub Desktop.
Python priority queue (with priority updating) built on top of heapq
from heapq import heappush, heappop
import itertools
__all__ = ["PriorityQueue"]
class PriorityQueue:
sentinel = object()
def __init__(self):
self.heap, self.entries = [], {}
self.counter = itertools.count()
def push(self, item, priority):
if item in self.entries:
self.entries[item][2] = self.sentinel
entry = self.entries[item] = [priority, next(self.counter), item]
heappush(self.heap, entry)
def pop(self):
while True:
priority, count, item = heappop(self.heap)
if item is not self.sentinel:
del self.entries[item]
return item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment