Created
May 22, 2020 09:55
-
-
Save joshlk/77ae67ba3c66aa348f79c36a299dc577 to your computer and use it in GitHub Desktop.
A PriorityQueue or MinHeap implementation. Items with the smallest cost are popped first. Object orientated interface for `heapq` (Python standard library).
This file contains 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
import heapq | |
class PriorityQueue: | |
""" | |
A PriorityQueue or MinHeap implementation. | |
Items with the smallest cost are popped first. | |
""" | |
def __init__(self): | |
self.h = [] | |
self.idx = -1 | |
def push(self, cost, item): | |
self.idx += 1 | |
heapq.heappush(self.h, (cost, self.idx, item)) | |
def pop(self): | |
cost, _, item = heapq.heappop(self.h) | |
return cost, item | |
def peek(self): | |
return self[0] | |
def __getitem__(self, i): | |
cost, _, item = self.h[i] | |
return cost, item | |
def __len__(self): | |
return len(self.h) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment