If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Certainly! In this part, we'll continue enhancing our Heap class by adding more functionalities such as updating an element's value and deleting an element from the heap.
Here's the next part of the Heap class, including element update and deletion:
pythonCopy code
class MaxHeap: # ... (previous code) def update_value(self, index, new_value): if index < 0 or index >= len(self.heap): return old_value = self.heap[index] self.heap[index] = new_value if new_value > old_value: self._heapify_up(index) else: self._heapify_down(index) def delete(self, value): if value not in self.heap: return index = self.heap.index(value) self.heap[index] = float('inf') self._heapify_up(index) self.extract_max() # Example usage max_heap = MaxHeap() max_heap.build_heap([5, 10, 3, 8, 2]) print("Max Heap before updating:") print(max_heap.heap) max_heap.update_value(2, 12) print("Max Heap after updating element at index 2:") print(max_heap.heap) max_heap.delete(12) print("Max Heap after deleting value 12:") print(max_heap.heap)
In this part, we've added the following functionalities to the Heap class:
Update Value: The update_value method allows you to update the value of an element at a specific index in the heap. It adjusts the position of the element in the heap by comparing the new value with the old value and performing either _heapify_up or _heapify_down as needed.
Delete Element: The delete method allows you to delete a specific value from the heap. It replaces the value to be deleted with positive infinity, performs _heapify_up to move the element to the root if needed, and then extracts the maximum value from the heap.
The example usage section demonstrates how to use the update_value method to update an element's value and the delete method to delete a specific value from the Max Heap.
These additions further extend the capabilities of the Heap class, allowing you to modify elements and delete values while maintaining the max heap property.
I bought this course, it worth it!
Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it
Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website
Quick answers to common questions about our courses, quizzes, and learning platform
SCIAKU Team please upload 1st video of TREE please please please, please