|
3 | 3 | from collections.abc import Callable |
4 | 4 | from typing import Any |
5 | 5 |
|
6 | | -from book.chapter6.section1 import left |
7 | | -from book.chapter6.section1 import right |
| 6 | +from book.chapter6.section1 import parent |
8 | 7 | from book.data_structures import Array |
9 | 8 | from book.data_structures import CT |
10 | 9 | from book.data_structures import Heap |
@@ -40,28 +39,15 @@ def assertArrayPermuted(self, array: Array[T], elements: list[T], end: int, star |
40 | 39 | if not match: |
41 | 40 | self.fail(msg) |
42 | 41 |
|
43 | | - def assertHeap(self, heap: Heap[CT], cmp: Callable[[Any, Any], bool]) -> None: |
44 | | - msg = f'Array {heap} is not a max-heap' |
45 | | - |
46 | | - def assertMaxSubheap(i: int) -> None: |
47 | | - l = left(i) |
48 | | - if l <= heap.heap_size: |
49 | | - if not cmp(heap[i], heap[l]): |
50 | | - self.fail(msg) |
51 | | - assertMaxSubheap(l) |
52 | | - r = right(i) |
53 | | - if r <= heap.heap_size: |
54 | | - if not cmp(heap[i], heap[r]): |
55 | | - self.fail(msg) |
56 | | - assertMaxSubheap(r) |
57 | | - |
58 | | - assertMaxSubheap(1) |
| 42 | + def assertHeap(self, heap: Heap[CT], heap_property: Callable[[int], bool]) -> None: |
| 43 | + for i in range_of(2, to=heap.heap_size): |
| 44 | + self.assertTrue(heap_property(i)) |
59 | 45 |
|
60 | 46 | def assertMaxHeap(self, heap: Heap[CT]) -> None: |
61 | | - self.assertHeap(heap, operator.ge) |
| 47 | + self.assertHeap(heap, lambda i: heap[parent(i)] >= heap[i]) |
62 | 48 |
|
63 | 49 | def assertMinHeap(self, heap: Heap[CT]) -> None: |
64 | | - self.assertHeap(heap, operator.le) |
| 50 | + self.assertHeap(heap, lambda i: heap[parent(i)] <= heap[i]) |
65 | 51 |
|
66 | 52 | def assertPriorityQueueMappingConsistent(self, queue: PriorityQueue) -> None: |
67 | 53 | for i in range_of(1, to=queue.heap_size): |
|
0 commit comments