|
18 | 18 | from solutions.chapter6.section5.exercise3 import min_heap_extract_min |
19 | 19 | from solutions.chapter6.section5.exercise3 import min_heap_insert |
20 | 20 | from solutions.chapter6.section5.exercise3 import min_heap_minimum |
| 21 | +from solutions.chapter6.section5.exercise4 import max_heap_decrease_key |
21 | 22 | from test_case import ClrsTestCase |
22 | 23 | from test_util import create_heap |
23 | 24 | from util import range_of |
@@ -192,3 +193,42 @@ def test_min_heap_insert_overflow(self, data): |
192 | 193 | self.assertEqual(A.heap_size, n) |
193 | 194 | self.assertArrayPermuted(A, key_objects, end=n) |
194 | 195 | self.assertPriorityQueueMappingConsistent(A) |
| 196 | + |
| 197 | + @given(st.data()) |
| 198 | + def test_max_heap_decrease_key(self, data): |
| 199 | + keys = data.draw(lists(integers(), min_size=1)) |
| 200 | + key_objects = [KeyObject(key, data.draw(text())) for key in keys] |
| 201 | + heap = create_heap(key_objects) |
| 202 | + n = len(key_objects) |
| 203 | + build_max_heap(heap, n) |
| 204 | + A = PriorityQueue(heap, n) |
| 205 | + x = random.choice(key_objects) |
| 206 | + k = x.key - data.draw(integers(min_value=0)) |
| 207 | + |
| 208 | + max_heap_decrease_key(A, x, k) |
| 209 | + |
| 210 | + self.assertEqual(x.key, k) |
| 211 | + self.assertEqual(A.heap_size, n) |
| 212 | + self.assertMaxHeap(A) |
| 213 | + self.assertArrayPermuted(A, key_objects, end=n) |
| 214 | + self.assertPriorityQueueMappingConsistent(A) |
| 215 | + |
| 216 | + @given(st.data()) |
| 217 | + def test_max_heap_decrease_key_invalid_key(self, data): |
| 218 | + keys = data.draw(lists(integers(), min_size=1)) |
| 219 | + key_objects = [KeyObject(key, data.draw(text())) for key in keys] |
| 220 | + heap = create_heap(key_objects) |
| 221 | + n = len(key_objects) |
| 222 | + build_max_heap(heap, n) |
| 223 | + A = PriorityQueue(heap, n) |
| 224 | + x = random.choice(key_objects) |
| 225 | + k = x.key + data.draw(integers(min_value=1)) |
| 226 | + |
| 227 | + with self.assertRaisesRegex(ValueError, "new key is larger than current key"): |
| 228 | + max_heap_decrease_key(A, x, k) |
| 229 | + |
| 230 | + self.assertNotEquals(x.key, k) |
| 231 | + self.assertMaxHeap(A) |
| 232 | + self.assertEqual(A.heap_size, n) |
| 233 | + self.assertArrayPermuted(A, key_objects, end=n) |
| 234 | + self.assertPriorityQueueMappingConsistent(A) |
0 commit comments