2020-07-11 09:02:32 +08:00
|
|
|
import unittest
|
2017-03-30 17:39:53 +08:00
|
|
|
|
|
|
|
|
2020-07-11 09:02:32 +08:00
|
|
|
class TestMinHeap(unittest.TestCase):
|
2017-03-30 17:39:53 +08:00
|
|
|
|
|
|
|
def test_min_heap(self):
|
|
|
|
heap = MinHeap()
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(heap.peek_min(), None)
|
|
|
|
self.assertEqual(heap.extract_min(), None)
|
2017-03-30 17:39:53 +08:00
|
|
|
heap.insert(20)
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(heap.array[0], 20)
|
2017-03-30 17:39:53 +08:00
|
|
|
heap.insert(5)
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(heap.array[0], 5)
|
|
|
|
self.assertEqual(heap.array[1], 20)
|
2017-03-30 17:39:53 +08:00
|
|
|
heap.insert(15)
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(heap.array[0], 5)
|
|
|
|
self.assertEqual(heap.array[1], 20)
|
|
|
|
self.assertEqual(heap.array[2], 15)
|
2017-03-30 17:39:53 +08:00
|
|
|
heap.insert(22)
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(heap.array[0], 5)
|
|
|
|
self.assertEqual(heap.array[1], 20)
|
|
|
|
self.assertEqual(heap.array[2], 15)
|
|
|
|
self.assertEqual(heap.array[3], 22)
|
2017-03-30 17:39:53 +08:00
|
|
|
heap.insert(40)
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(heap.array[0], 5)
|
|
|
|
self.assertEqual(heap.array[1], 20)
|
|
|
|
self.assertEqual(heap.array[2], 15)
|
|
|
|
self.assertEqual(heap.array[3], 22)
|
|
|
|
self.assertEqual(heap.array[4], 40)
|
2017-03-30 17:39:53 +08:00
|
|
|
heap.insert(3)
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(heap.array[0], 3)
|
|
|
|
self.assertEqual(heap.array[1], 20)
|
|
|
|
self.assertEqual(heap.array[2], 5)
|
|
|
|
self.assertEqual(heap.array[3], 22)
|
|
|
|
self.assertEqual(heap.array[4], 40)
|
|
|
|
self.assertEqual(heap.array[5], 15)
|
2017-03-30 17:39:53 +08:00
|
|
|
mins = []
|
|
|
|
while heap:
|
|
|
|
mins.append(heap.extract_min())
|
2020-07-11 09:02:32 +08:00
|
|
|
self.assertEqual(mins, [3, 5, 15, 20, 22, 40])
|
2017-03-30 17:39:53 +08:00
|
|
|
print('Success: test_min_heap')
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
test = TestMinHeap()
|
|
|
|
test.test_min_heap()
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2020-07-11 09:02:32 +08:00
|
|
|
main()
|