Skip to content

Instantly share code, notes, and snippets.

@joshlk
Created May 22, 2020 09:55
Show Gist options
  • Save joshlk/77ae67ba3c66aa348f79c36a299dc577 to your computer and use it in GitHub Desktop.
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).
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