SHARE
TWEET

Untitled

a guest Jun 17th, 2019 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. h = []
  2. heapq.heappush(h,(10, 1200))
  3. heapq.heappush(h,(20, 31))
  4. heapq.heappush(h,(5, 1))
  5.      
  6. if len(h) < capacity:
  7.     heapq.heappush(h, thing)
  8. else:
  9.     # Equivalent to a push, then a pop, but faster
  10.     spilled_value = heapq.heappushpop(h, thing)
  11.     do_whatever_with(spilled_value)
  12.      
  13. from heapq import heapify, heappush, heappushpop
  14.  
  15. class MaxHeap():
  16.     def __init__(self, top_n):
  17.         self.h = []
  18.         self.length = top_n
  19.         heapify( self.h)
  20.  
  21.     def add(self, element):
  22.         if len(self.h) < self.length:
  23.             heappush(self.h, element)
  24.         else:
  25.             heappushpop(self.h, element)
  26.  
  27.     def getTop(self):
  28.         return sorted(self.h, reverse=True)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top