Skip to content

Instantly share code, notes, and snippets.

@jovianlin
Created December 21, 2018 10:16
Show Gist options
  • Save jovianlin/d56be342ec55e034c687dbd148a08770 to your computer and use it in GitHub Desktop.
Save jovianlin/d56be342ec55e034c687dbd148a08770 to your computer and use it in GitHub Desktop.
Python3 MinHeap and MaxHeap
class MaxHeapObj:
def __init__(self,val): self.val = val
def __lt__(self,other): return self.val > other.val
def __eq__(self,other): return self.val == other.val
def __str__(self): return str(self.val)
class MinHeap:
def __init__(self): self.h = []
def heappush(self,x): heapq.heappush(self.h,x)
def heappop(self): return heapq.heappop(self.h)
def __getitem__(self,i): return self.h[i]
def __len__(self): return len(self.h)
class MaxHeap(MinHeap):
def heappush(self,x): heapq.heappush(self.h,MaxHeapObj(x))
def heappop(self): return heapq.heappop(self.h).val
def __getitem__(self,i): return self.h[i].val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment