Created
April 2, 2020 06:46
-
-
Save AntiKnot/2ad665271ca6db94def1e4a252bb2735 to your computer and use it in GitHub Desktop.
python heapq topk
This file contains hidden or 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
| import heapq | |
| class TopK(object): | |
| def __init__(self, k): | |
| self.k = k | |
| self.heap = [] | |
| def push(self, elem): | |
| if len(self.heap) < self.k: | |
| heapq.heappush(self.heap, elem) | |
| elif elem > self.heap[0]: | |
| heapq.heapreplace(self.heap, elem) | |
| def topk(self): | |
| return list(heapq.heappop(self.heap) for _ in range(len(self.heap)))[::-1] | |
| class BtmK(object): | |
| def __init__(self, k): | |
| self.k = k | |
| self.heap = [] | |
| def push(self, elem): | |
| if len(self.heap) < self.k: | |
| heapq.heappush(self.heap, -elem) | |
| elif elem < -self.heap[0]: | |
| heapq.heapreplace(self.heap, -elem) | |
| def btmk(self): | |
| return list(-heapq.heappop(self.heap) for _ in range(len(self.heap)))[::-1] | |
| if __name__ == '__main__': | |
| nums = [1, 7, 4, 43, 11, 5, 54, 42, 3, 13, 33] | |
| top4 = TopK(4) | |
| for num in nums: | |
| top4.push(num) | |
| print(top4.topk()) | |
| btm4 = BtmK(4) | |
| for num in nums: | |
| btm4.push(num) | |
| print(btm4.btmk()) | |
| """ | |
| ref | |
| https://docs.python.org/3.5/library/heapq.html | |
| https://www.coder4.com/archives/3844 | |
| https://blog.csdn.net/tanghaiyu777/article/details/55271004 | |
| https://www.jianshu.com/p/801318c77ab5 | |
| """ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment