import heapq
class TopK:
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():
import random
i = list(range(1000))
random.shuffle(i)
_ = TopK(i, 10)
print(_.get_topk())
if __name__ == '__main__':
test()
手机扫一扫
移动阅读更方便
你可能感兴趣的文章