Skip to content

Commit 6239e26

Browse files
committed
use a heap property lambda in asserting if a heap is valid
1 parent 5bfe866 commit 6239e26

File tree

1 file changed

+6
-20
lines changed

1 file changed

+6
-20
lines changed

test/test_case.py

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
from collections.abc import Callable
44
from typing import Any
55

6-
from book.chapter6.section1 import left
7-
from book.chapter6.section1 import right
6+
from book.chapter6.section1 import parent
87
from book.data_structures import Array
98
from book.data_structures import CT
109
from book.data_structures import Heap
@@ -40,28 +39,15 @@ def assertArrayPermuted(self, array: Array[T], elements: list[T], end: int, star
4039
if not match:
4140
self.fail(msg)
4241

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))
5945

6046
def assertMaxHeap(self, heap: Heap[CT]) -> None:
61-
self.assertHeap(heap, operator.ge)
47+
self.assertHeap(heap, lambda i: heap[parent(i)] >= heap[i])
6248

6349
def assertMinHeap(self, heap: Heap[CT]) -> None:
64-
self.assertHeap(heap, operator.le)
50+
self.assertHeap(heap, lambda i: heap[parent(i)] <= heap[i])
6551

6652
def assertPriorityQueueMappingConsistent(self, queue: PriorityQueue) -> None:
6753
for i in range_of(1, to=queue.heap_size):

0 commit comments

Comments
 (0)