getMin(self) needs to return the minimum value in the heap
_parent(self, index) it needs to return value of the parent of the element at the specific index
_leftChild(self, index) and _right Child(self,index) return value of the left/right child of the element at the specific index
insert(self, item) needs to insert an item into the heap while maintaining the minimum heap property. It must use the _parent method.
Starter Code
def __init__(self):
self._heap=[]
def __str__(self):
return f'{self._heap}'
__repr__=__str__
def __len__(self):
return len(self._heap)
@property
def getMin(self):
# YOUR CODE STARTS HERE
pass
def _parent(self,index):
# YOUR CODE STARTS HERE
pass
def _leftChild(self,index):
# YOUR CODE STARTS HERE
pass
def _rightChild(self,index):
# YOUR CODE STARTS HERE
pass
def insert(self,item):
# YOUR CODE STARTS HERE
pass
The image is for a note.
Please help with the bold codes.
Expected output
>>> h = MinBinaryHeap()
>>> h.insert(10)
>>> h.insert(5)
>>> h
[5, 10]
>>> h.insert(14)
>>> h._heap
[5, 10, 14]
>>> h.insert(9)
>>> h
[5, 9, 14, 10]
>>> h.insert(2)
>>> h
[2, 5, 14, 10, 9]
>>> h.insert(11)
>>> h
[2, 5, 11, 10, 9, 14]
>>> h.insert(14)
>>> h
[2, 5, 11, 10, 9, 14, 14]
>>> h.insert(20)
>>> h
[2, 5, 11, 10, 9, 14, 14, 20]
>>> h.insert(20)
>>> h
[2, 5, 11, 10, 9, 14, 14, 20, 20]
>>> h.getMin
2
>>> h._leftChild(1)
5
>>> h._rightChild(1)
11
>>> h._parent(1)
>>> h._parent(6)
11
>>> h._leftChild(6)
>>> h._rightChild(9)
>>> h.deleteMin()
2
>>> h._heap
[5, 9, 11, 10, 20, 14, 14, 20]
>>> h.deleteMin()
5
>>> h
[9, 10, 11, 20, 20, 14, 14]
>>> len(h)
7
>>> h.getMin
9
'''
Extracted text: Please note that the index passed into the _parent,_leftChild and_rightChild methods are 1-indexed (as heap indices usually are), but a Python list is 0-indexed. Make sure to adjust your formulas for this (do not leave an empty space in the 0th index of self._heap). Неаp index: 1 Python List Index: 0 5 Неаp index: 2 Python List Index: 1 Heap index: 3 Python List Index: 2 14 11 Неаp index 4 Python List Index: 3 54 >>> x = MinBinaryHeap() >>> x._heap = [5, 14, 11, 54] # force load a minimum heap >>> x._parent(4) # Heap index 4 (value: 54) has a parent at index 14 # 4//2 =2, which is list index 1 (x._heap[1]) >>> x._leftChild(2) # Heap index 2 (value: 14) has a left child at index 54 # 2 * 2 = 4, which is list index 3 (x._heap[3]) >>> x._rightChild(1) # Heap index 1 (value: 5) has a right child at index # 2 * 1 + 1 = 3, which is list index 2 (x._heap[2]) 11