-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxheap.py
37 lines (30 loc) · 979 Bytes
/
maxheap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python3
# https://stackoverflow.com/questions/30443150/maintain-a-fixed-size-heap-python
from heapq import heapify, heappush, heappop, heappushpop, nlargest
class MaxHeap():
def __init__(self, top_n):
self.h = []
self.maxsize = top_n
heapify(self.h)
def add(self, element):
if len(self.h) < self.maxsize:
heappush(self.h, element)
else:
heappushpop(self.h, element)
def top(self, count=None):
if not count: count = len(self.h)
return nlargest(count, self.h)
def get_list(self):
return self.h
def reset(self, new_h, top_n=None):
if new_h:
self.maxsize = len(new_h)
self.h = new_h
heapify(self.h)
if top_n:
self.maxsize = top_n
while len(self.h) > self.maxsize: heappop(self.h)
else:
self.h = []
self.maxsize = None
return