forked from ls1248659692/python_guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_heap_topk.py
More file actions
41 lines (31 loc) · 841 Bytes
/
binary_heap_topk.py
File metadata and controls
41 lines (31 loc) · 841 Bytes
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
38
39
40
41
#!/usr/bin/python
# coding=utf8
import heapq
import random
__author__ = 'Jam'
__date__ = '2019/5/30 16:00'
class TopK(object):
def __init__(self, iterable, k):
self.minheap = []
self.capacity = k
self.iterable = iterable
def push(self, val):
if len(self.minheap) >= self.capacity:
min_val = self.minheap[0]
if val < min_val:
pass
else:
heapq.heapreplace(self.minheap, val)
else:
heapq.heappush(self.minheap, val)
def get_topk(self):
for val in self.iterable:
self.push(val)
return self.minheap
def test():
number_list = list(range(1000))
random.shuffle(number_list)
topk = TopK(number_list, 10)
print topk.get_topk()
if __name__ == '__main__':
test()