def test_nbest(self): # Less-naive "N-best" algorithm, much faster (if len(data) is big # enough <wink>) than sorting all of data. However, if we had a max # heap instead of a min heap, it could go faster still via # heapify'ing all of data (linear time), then doing 10 heappops # (10 log-time steps). data = [random.randrange(2000) for _ in xrange(1000)] heap = self.makeHeap(data[:10]) key = self.key or (lambda x:x) for item in data[10:]: if key(item) > key(heap[0]): # this gets rarer the longer we run heap.replace(item) assert list(heap.iterpop()) == self.sorted(data)[-10:]
def test_replace(self): heap = self.makeHeap([16,12,18,15]) m = self.min(heap); assert heap.replace(13) == m; assert 13 in heap m = self.min(heap); assert heap.pushpop(17) == m; assert 17 in heap assert self.makeHeap().pushpop(4) == 4 py.test.raises(TypeError, heap.replace, None, None) # replace fails on an empty heap py.test.raises(IndexError, self.makeHeap().replace, 1)