How to Implement Binary Heap in Python
In this tutorial, we will learn how to program “How to Implement a Binary Heap in Python.” The main objective is to understand how binary heap operations work and how they are implemented in Python. This tutorial will guide you step by step through the process of using binary heap operations, such as insertion, deletion, and heapify, within a program. By the end of this tutorial, you will have a clear understanding of how to work with binary heaps, helping you strengthen your problem-solving abilities and improve your overall coding skills.
This topic is straightforward and easy to understand. By simply following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of checking whether an expression is correctly parenthesized. So, let’s dive into the coding process and start implementing the solution!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- class BinaryHeap:
- def __init__(self):
- self.items = []
- def size(self):
- return len(self.items)
- def parent(self, i):
- return (i - 1) // 2
- def left(self, i):
- return 2 * i + 1
- def right(self, i):
- return 2 * i + 2
- def get(self, i):
- return self.items[i]
- def get_max(self):
- if self.size() == 0:
- return None
- return self.items[0]
- def extract_max(self):
- if self.size() == 0:
- return None
- largest = self.get_max()
- self.items[0] = self.items[-1]
- self.items.pop()
- self.max_heapify(0)
- return largest
- def max_heapify(self, i):
- l = self.left(i)
- r = self.right(i)
- largest = i
- if l < self.size() and self.get(l) > self.get(largest):
- largest = l
- if r < self.size() and self.get(r) > self.get(largest):
- largest = r
- if largest != i:
- self.swap(i, largest)
- self.max_heapify(largest)
- def swap(self, i, j):
- self.items[i], self.items[j] = self.items[j], self.items[i]
- def insert(self, key):
- self.items.append(key)
- index = self.size() - 1
- while index != 0 and self.get(self.parent(index)) < self.get(index):
- self.swap(index, self.parent(index))
- index = self.parent(index)
- def display(self):
- if self.size() == 0:
- print("Heap is empty.")
- else:
- print("Heap elements:", self.items)
- # MAIN PROGRAM
- while True:
- print("\n=============== Implement Binary Heap (Max Heap) ===============\n")
- bheap = BinaryHeap()
- while True:
- print("\nMenu:")
- print("insert <data>")
- print("max get")
- print("max extract")
- print("display")
- print("quit")
- do = input("What would you like to do? ").split()
- if not do:
- continue
- operation = do[0].lower()
- if operation == "insert":
- if len(do) != 2:
- print("Usage: insert <data>")
- else:
- bheap.insert(int(do[1]))
- print("Value inserted.")
- elif operation == "max":
- if len(do) != 2:
- print("Usage: max get | max extract")
- else:
- sub = do[1].lower()
- if sub == "get":
- print("Maximum value:", bheap.get_max())
- elif sub == "extract":
- print("Maximum value removed:", bheap.extract_max())
- else:
- print("Invalid max command.")
- elif operation == "display":
- bheap.display()
- elif operation == "quit":
- break
- else:
- print("Invalid command.")
- # Try again option
- opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
- if opt == "no":
- print("Exiting program...")
- break
- elif opt != "yes":
- print("Invalid choice. Exiting program...")
- break
This program implements a binary max heap data structure using a Python list and provides an interactive menu for performing heap operations. The `BinaryHeap` class supports inserting elements while maintaining the max-heap property, retrieving the maximum value, extracting (removing) the maximum element, and displaying the heap contents. Internally, it uses helper methods to compute parent and child indices, swap elements, and restore the heap property through the `max_heapify` process after deletions. The main loop allows users to repeatedly insert values, view or extract the maximum element, and display the current state of the heap until they choose to exit, making it a clear demonstration of how a max heap works in practice.
Output:
There you have it we successfully created How to Implement Binary Heap in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language