blob: f37d8ff6211371d41e3155d59b494f120c838d30 [file] [log] [blame]
Guido van Rossum0b191782002-08-02 18:29:53 +00001"""Unittests for heapq."""
2
Raymond Hettinger33ecffb2004-06-10 05:03:17 +00003from heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest
Guido van Rossum0b191782002-08-02 18:29:53 +00004import random
Raymond Hettingerbce036b2004-06-10 05:07:18 +00005import unittest
6from test import test_support
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +00007import sys
Guido van Rossum0b191782002-08-02 18:29:53 +00008
Guido van Rossum0b191782002-08-02 18:29:53 +00009
Raymond Hettingerbce036b2004-06-10 05:07:18 +000010def heapiter(heap):
11 # An iterator returning a heap's elements, smallest-first.
12 try:
13 while 1:
14 yield heappop(heap)
15 except IndexError:
16 pass
Tim Petersaa7d2432002-08-03 02:11:26 +000017
Raymond Hettingerbce036b2004-06-10 05:07:18 +000018class TestHeap(unittest.TestCase):
Tim Petersaa7d2432002-08-03 02:11:26 +000019
Raymond Hettingerbce036b2004-06-10 05:07:18 +000020 def test_push_pop(self):
21 # 1) Push 256 random numbers and pop them off, verifying all's OK.
22 heap = []
23 data = []
24 self.check_invariant(heap)
25 for i in range(256):
26 item = random.random()
27 data.append(item)
28 heappush(heap, item)
29 self.check_invariant(heap)
30 results = []
31 while heap:
32 item = heappop(heap)
33 self.check_invariant(heap)
34 results.append(item)
35 data_sorted = data[:]
36 data_sorted.sort()
37 self.assertEqual(data_sorted, results)
38 # 2) Check that the invariant holds for a sorted array
39 self.check_invariant(results)
40
Neal Norwitzd7be1182004-07-08 01:56:46 +000041 self.assertRaises(TypeError, heappush, [])
42 self.assertRaises(TypeError, heappush, None, None)
43 self.assertRaises(TypeError, heappop, None)
44
Raymond Hettingerbce036b2004-06-10 05:07:18 +000045 def check_invariant(self, heap):
46 # Check the heap invariant.
47 for pos, item in enumerate(heap):
48 if pos: # pos 0 has no parent
49 parentpos = (pos-1) >> 1
50 self.assert_(heap[parentpos] <= item)
51
52 def test_heapify(self):
53 for size in range(30):
54 heap = [random.random() for dummy in range(size)]
55 heapify(heap)
56 self.check_invariant(heap)
57
Neal Norwitzd7be1182004-07-08 01:56:46 +000058 self.assertRaises(TypeError, heapify, None)
59
Raymond Hettingerbce036b2004-06-10 05:07:18 +000060 def test_naive_nbest(self):
61 data = [random.randrange(2000) for i in range(1000)]
62 heap = []
63 for item in data:
64 heappush(heap, item)
65 if len(heap) > 10:
66 heappop(heap)
67 heap.sort()
68 self.assertEqual(heap, sorted(data)[-10:])
69
70 def test_nbest(self):
71 # Less-naive "N-best" algorithm, much faster (if len(data) is big
72 # enough <wink>) than sorting all of data. However, if we had a max
73 # heap instead of a min heap, it could go faster still via
74 # heapify'ing all of data (linear time), then doing 10 heappops
75 # (10 log-time steps).
76 data = [random.randrange(2000) for i in range(1000)]
77 heap = data[:10]
78 heapify(heap)
79 for item in data[10:]:
80 if item > heap[0]: # this gets rarer the longer we run
81 heapreplace(heap, item)
82 self.assertEqual(list(heapiter(heap)), sorted(data)[-10:])
83
Neal Norwitzd7be1182004-07-08 01:56:46 +000084 self.assertRaises(TypeError, heapreplace, None)
85 self.assertRaises(TypeError, heapreplace, None, None)
86 self.assertRaises(IndexError, heapreplace, [], None)
87
Raymond Hettingerbce036b2004-06-10 05:07:18 +000088 def test_heapsort(self):
89 # Exercise everything with repeated heapsort checks
90 for trial in xrange(100):
91 size = random.randrange(50)
92 data = [random.randrange(25) for i in range(size)]
93 if trial & 1: # Half of the time, use heapify
94 heap = data[:]
95 heapify(heap)
96 else: # The rest of the time, use heappush
97 heap = []
98 for item in data:
99 heappush(heap, item)
100 heap_sorted = [heappop(heap) for i in range(size)]
101 self.assertEqual(heap_sorted, sorted(data))
102
103 def test_nsmallest(self):
104 data = [random.randrange(2000) for i in range(1000)]
Raymond Hettingeraefde432004-06-15 23:53:35 +0000105 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
106 self.assertEqual(nsmallest(n, data), sorted(data)[:n])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000107
108 def test_largest(self):
109 data = [random.randrange(2000) for i in range(1000)]
Raymond Hettingeraefde432004-06-15 23:53:35 +0000110 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
111 self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n])
Tim Petersaa7d2432002-08-03 02:11:26 +0000112
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000113def test_main(verbose=None):
114 test_classes = [TestHeap]
115 test_support.run_unittest(*test_classes)
116
117 # verify reference counting
118 if verbose and hasattr(sys, "gettotalrefcount"):
119 import gc
120 counts = [None] * 5
121 for i in xrange(len(counts)):
122 test_support.run_unittest(*test_classes)
123 gc.collect()
124 counts[i] = sys.gettotalrefcount()
125 print counts
Guido van Rossum0b191782002-08-02 18:29:53 +0000126
127if __name__ == "__main__":
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000128 test_main(verbose=True)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000129