def test_sorted(self): l = range(10, -1, -1) MaxHeap.build_heap(l) h = MaxHeap() h.items = l new_l = [] h.sorted(lambda i, l: l.append(i), new_l) assert new_l == range(10, -1, -1)
def test_custom_items(self): class Record: def __init__(self, a, b, c): self.a = a self.b = b self.c = c # by default, using 'b' as key to compare def __cmp__(self, other): return cmp(self.b, other.b) def __str__(self): return "(%s, %s, %s)" % (self.a, self.b, self.c) h = MaxHeap() h.add(Record("record1", 1, 100)) h.add(Record("record4", 5, 125)) h.add(Record("record3", 2, 50)) h.add(Record("record2", 3, 25)) h.add(Record("record5", 4, 5)) sorted_records_bs = [] h.sorted(lambda x, l: l.append(x.b), sorted_records_bs) assert sorted_records_bs == range(5, 0, -1) h2 = MaxHeap(lambda r1, r2: cmp(r1.a, r2.a)) h2.add(Record("record1", 1, 100)) h2.add(Record("record4", 5, 125)) h2.add(Record("record3", 2, 50)) h2.add(Record("record2", 3, 25)) h2.add(Record("record5", 4, 5)) sorted_records_as = [] h2.sorted(lambda x, l: l.append(x.a), sorted_records_as) assert sorted_records_as == [ "record" + str(i) for i in xrange(5, 0, -1) ] h3 = MaxHeap(lambda r1, r2: cmp(r1.c, r2.c)) h3.add(Record("record1", 1, 100)) h3.add(Record("record4", 5, 125)) h3.add(Record("record3", 2, 50)) h3.add(Record("record2", 3, 25)) h3.add(Record("record5", 4, 5)) sorted_records_cs = [] h3.sorted(lambda x, l: l.append(x.c), sorted_records_cs) assert sorted_records_cs == sorted([100, 125, 50, 25, 5])[::-1]