Skip to content

Commit 5bfe866

Browse files
committed
#75 multiary_parent, multiary_child
1 parent e445b3d commit 5bfe866

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

src/solutions/chapter6/problem2.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from util import ceil_div
2+
3+
4+
def multiary_parent(d: int, i: int) -> int:
5+
"""The index of the parent of a multiary heap node.
6+
7+
Implements:
8+
Multiary-Parent
9+
10+
Args:
11+
d: the arity of the heap, d >= 2
12+
i: the index of the node
13+
14+
Returns:
15+
The index of the parent of the node at index i in a d-ary heap.
16+
"""
17+
return ceil_div(i - 1, d)
18+
19+
20+
def multiary_child(d: int, i: int, k: int) -> int:
21+
"""The index of a child of a multiary heap node.
22+
23+
Implements:
24+
Multiary-Child
25+
26+
Args:
27+
d: the arity of the heap, d >= 2
28+
i: the index of the node
29+
k: the number of a child to get, 1 <= k <= d
30+
31+
Returns:
32+
The index of the k-th child of the node at index i in a d-ary heap.
33+
"""
34+
return d * (i - 1) + k + 1

test/test_solutions/test_chapter6.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
from book.data_structures import Heap
1313
from book.data_structures import KeyObject
1414
from book.data_structures import PriorityQueue
15+
from solutions.chapter6.problem2 import multiary_child
16+
from solutions.chapter6.problem2 import multiary_parent
1517
from solutions.chapter6.section2.exercise3 import min_heapify
1618
from solutions.chapter6.section2.exercise6 import iterative_max_heapify
1719
from solutions.chapter6.section5.exercise3 import min_heap_decrease_key
@@ -272,3 +274,13 @@ def test_max_heap_increase_key__invalid_key(self, data):
272274
self.assertEqual(A.heap_size, n)
273275
self.assertArrayPermuted(A, key_objects, end=n)
274276
self.assertPriorityQueueMappingConsistent(A)
277+
278+
@given(st.data())
279+
def test_multiary_parent_child(self, data):
280+
d = data.draw(integers(min_value=2, max_value=20))
281+
i = data.draw(integers(min_value=1))
282+
k = data.draw(integers(min_value=1, max_value=d))
283+
284+
actual_node_index = multiary_parent(d, multiary_child(d, i, k))
285+
286+
self.assertEqual(actual_node_index, i)

0 commit comments

Comments
 (0)