When heappush () is used, the heap sequence of elements is maintained when new elements are added from the data source. Delete an existing element in an operation and replace it with a new value. You can use heapreplace ()
Import heapq
Class BtmkHeap (object ): Def _ init _ (self, k ): Self. k = k Self. data = []
Def Push (self, elem ): # Reverse elem to convert to max-heap Num1 = elem [0] Num1 =-num1 Num2 = elem [1] # Using heap algorighem If len (self. data) <self. k: Heapq. heappush (self. data, (num1, num2 )) Else: Topk_small = self. data [0] [0] If elem [0]> topk_small: Heapq. heapreplace (self. data, (num1, num2 ))
Def BtmK (self ): Return sorted ([(-x [0], x [1]) for x in self. data])
If _ name _ = '_ main __': A = (100,1) B = (200,2) C =) D = (400,4) E = (50, 5) Btm = BtmkHeap (3) Btm. Push () Btm. Push (B) Btm. Push (c) Btm. Push (e) Btm. Push (23,1 )) Print (btm. BtmK ())
Result [(23, 1), (50, 5), (100, 1)]
|