MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / parent_index

Method parent_index

data_structures/heap/heap.py:55–89  ·  view source on GitHub ↗

returns the parent index based on the given child index >>> h = Heap() >>> h.build_max_heap([103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5]) >>> h [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> h.parent_index(-1) # returns none if index is <=0

(self, child_idx: int)

Source from the content-addressed store, hash-verified

53 return str(self.h)
54
55 def parent_index(self, child_idx: int) -> int | None:
56 """
57 returns the parent index based on the given child index
58
59 >>> h = Heap()
60 >>> h.build_max_heap([103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5])
61 >>> h
62 [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]
63
64 >>> h.parent_index(-1) # returns none if index is <=0
65
66 >>> h.parent_index(0) # returns none if index is <=0
67
68 >>> h.parent_index(1)
69 0
70 >>> h.parent_index(2)
71 0
72 >>> h.parent_index(3)
73 1
74 >>> h.parent_index(4)
75 1
76 >>> h.parent_index(5)
77 2
78 >>> h.parent_index(10.5)
79 4.0
80 >>> h.parent_index(209.0)
81 104.0
82 >>> h.parent_index("Test")
83 Traceback (most recent call last):
84 ...
85 TypeError: '>' not supported between instances of 'str' and 'int'
86 """
87 if child_idx > 0:
88 return (child_idx - 1) // 2
89 return None
90
91 def left_child_idx(self, parent_idx: int) -> int | None:
92 """

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected