def test_naive_nbest(self): data = [random.randrange(2000) for _ in xrange(1000)] heap = self.makeHeap() for item in data: heap.push(item) if len(heap) > 10: heap.popmin() assert list(heap.iterpop()) == self.sorted(data)[-10:]
def test_heapsort(self): # Exercise everything with repeated heapsort checks for trial in xrange(100): size = random.randrange(50) data = [random.randrange(25) for _ in xrange(size)] if trial & 1: # Half of the time, use heapify heap = self.makeHeap(data) else: # The rest of the time, use heappush heap = self.makeHeap() for item in data: heap.push(item) heap_sorted = [heap.popmin() for _ in xrange(size)] assert heap_sorted == self.sorted(data)
def test_push_pop(self): # push 256 random numbers and pop them off, verifying all's OK. heap = self.makeHeap() data = [] self.assert_heap_invariant(heap) for _ in xrange(256): item = random.random() data.append(item) heap.push(item) self.assert_heap_invariant(heap) results = [] while heap: item = heap.popmin() self.assert_heap_invariant(heap) results.append(item) assert self.sorted(data) == results # check that the invariant holds for a sorted array self.assert_heap_invariant(results) py.test.raises(TypeError, heap.push) py.test.raises(TypeError, heap.push, None, None) py.test.raises(TypeError, heap.popmin, None)