Skip to content

Instantly share code, notes, and snippets.

@Clivern
Created March 21, 2021 18:40
Show Gist options
  • Save Clivern/331bbc3ad467d5cc1716c0ea4f48445e to your computer and use it in GitHub Desktop.
Save Clivern/331bbc3ad467d5cc1716c0ea4f48445e to your computer and use it in GitHub Desktop.
Python Heap
from heapq import *
class Heap():
def __init__(self):
self.heap = []
def heappush(self, item):
"""Push the value item onto the heap, maintaining the heap invariant."""
heappush(self.heap, item)
def heappop(self):
"""Pop and return the smallest item from the heap, maintaining the heap invariant."""
return heappop(self.heap)
def heappushpop(self, item):
"""Push item on the heap, then pop and return the smallest item from the heap."""
return heappushpop(self.heap, item)
def heapreplace(self, item):
"""
Pop and return the smallest item from the heap, and also push the new item. The heap size doesn’t change.
If the heap is empty, IndexError is raised.
"""
return heapreplace(self.heap, item)
def size(self):
return len(self.heap)
def heapsort(self):
h = []
for value in self.heap:
heappush(h, value)
self.heap = [heappop(h) for i in range(len(h))]
def __repr__(self):
return str(self.heap)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment