Created
December 29, 2019 23:23
-
-
Save cppio/2a8d101bd601f25c0bf15ca741618cc5 to your computer and use it in GitHub Desktop.
Python priority queue (with priority updating) built on top of heapq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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