I have the task of making a Max Binary Heap class and I have made functions to find the left and right child. I have also made a function deleteMax that deletes the max number in the heap and sorts accordingly, But I made it without calling the first two functions and am not sure how to change the code accordingly.
class MaxBinaryHeap:
def __init__(self):
self._heap=[]
def __str__(self):
return f'{self._heap}'
__repr__=__str__
def __len__(self):
return len(self._heap)
@property
def getMax(self):
if len(self) == 0:
return None
else:
return self._heap[0]
def _parent(self,index):
if index <= 1 or index > len(self):
return None
else:
return self._heap[(index // 2)-1]
def _leftChild(self,index):
if 2*index < len(self):
return self._heap[(2 * index) - 1]
else:
return None
def _rightChild(self,index):
if (2*index) - 1 < len(self):
return self._heap[(2 * index)]
else:
return None
def insert(self,x):
self._heap.append(x)
current = len(self._heap) - 1
while self._parent(current + 1) is not None and self._heap[current] > self._parent(current + 1):
parent_current = ((current + 1) // 2) -1
self._heap[current], self._heap[parent_current] = self._heap[parent_current], self._heap[current]
current = parent_current
def deleteMax(self):
if len(self) == 0:
return None
elif len(self) == 1:
removed = self._heap[0]
self._heap = []
return removed
max_value = self._heap[0]
last_value = self._heap.pop()
self._heap[0] = last_value
current = 0
left_child_index = 2 * current + 1
right_child_index = 2 * current + 2
while left_child_index < len(self._heap):
swap_index = left_child_index
if (right_child_index < len(self._heap) and self._heap[right_child_index] > self._heap[left_child_index]):
swap_index = right_child_index
if self._heap[swap_index] > self._heap[current]:
self._heap[current], self._heap[swap_index] = self._heap[swap_index], self._heap[current]
current = swap_index
left_child_index = 2 * current + 1
right_child_index = 2 * current + 2
return max_value
thanks for posting the whole code, which makes it clear...
if you want to call a method inside a class, all you have to do is this:
in the example above, the return value of the
_leftChild()
method is assigned toleft_child_index
variable.It is up to you where to uses these (if you need to).