Created
June 10, 2020 22:25
-
-
Save erip/2d465882152c00ba188b4f0b09137f47 to your computer and use it in GitHub Desktop.
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
from heapq import heapify, heappush, heappushpop | |
class MaxHeap: | |
def __init__(self, top_n: int): | |
self.h = [] | |
self.length = top_n | |
heapify(self.h) | |
def add(self, element): | |
if len(self.h) < self.length: | |
heappush(self.h, element) | |
else: | |
heappushpop(self.h, element) | |
def get_top(self): | |
return sorted(self.h, reverse=True) | |
if __name__ == "__main__": | |
# no more than 5 elements | |
n_saved = 5 | |
heap = MaxHeap(top_n=n_saved) | |
checkpoints = list(range(10)) | |
for i in checkpoints: | |
heap.add(i) | |
assert heap.get_top() == checkpoints[:-n_saved-1:-1] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment