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.
  1. class BinaryHeap:
  2.     def __init__(self):
  3.         self.items = []
  4.  
  5.     def size(self):
  6.         return len(self.items)
  7.  
  8.     def parent(self, i):
  9.         return (i - 1) // 2
  10.  
  11.     def left(self, i):
  12.         return 2 * i + 1
  13.  
  14.     def right(self, i):
  15.         return 2 * i + 2
  16.  
  17.     def get(self, i):
  18.         return self.items[i]
  19.  
  20.     def get_max(self):
  21.         if self.size() == 0:
  22.             return None
  23.         return self.items[0]
  24.  
  25.     def extract_max(self):
  26.         if self.size() == 0:
  27.             return None
  28.         largest = self.get_max()
  29.         self.items[0] = self.items[-1]
  30.         self.items.pop()
  31.         self.max_heapify(0)
  32.         return largest
  33.  
  34.     def max_heapify(self, i):
  35.         l = self.left(i)
  36.         r = self.right(i)
  37.         largest = i
  38.  
  39.         if l < self.size() and self.get(l) > self.get(largest):
  40.             largest = l
  41.         if r < self.size() and self.get(r) > self.get(largest):
  42.             largest = r
  43.  
  44.         if largest != i:
  45.             self.swap(i, largest)
  46.             self.max_heapify(largest)
  47.  
  48.     def swap(self, i, j):
  49.         self.items[i], self.items[j] = self.items[j], self.items[i]
  50.  
  51.     def insert(self, key):
  52.         self.items.append(key)
  53.         index = self.size() - 1
  54.  
  55.         while index != 0 and self.get(self.parent(index)) < self.get(index):
  56.             self.swap(index, self.parent(index))
  57.             index = self.parent(index)
  58.  
  59.     def display(self):
  60.         if self.size() == 0:
  61.             print("Heap is empty.")
  62.         else:
  63.             print("Heap elements:", self.items)
  64.  
  65.  
  66. # MAIN PROGRAM
  67. while True:
  68.     print("\n=============== Implement Binary Heap (Max Heap) ===============\n")
  69.  
  70.     bheap = BinaryHeap()
  71.  
  72.     while True:
  73.         print("\nMenu:")
  74.         print("insert <data>")
  75.         print("max get")
  76.         print("max extract")
  77.         print("display")
  78.         print("quit")
  79.  
  80.         do = input("What would you like to do? ").split()
  81.         if not do:
  82.             continue
  83.  
  84.         operation = do[0].lower()
  85.  
  86.         if operation == "insert":
  87.             if len(do) != 2:
  88.                 print("Usage: insert <data>")
  89.             else:
  90.                 bheap.insert(int(do[1]))
  91.                 print("Value inserted.")
  92.  
  93.         elif operation == "max":
  94.             if len(do) != 2:
  95.                 print("Usage: max get | max extract")
  96.             else:
  97.                 sub = do[1].lower()
  98.                 if sub == "get":
  99.                     print("Maximum value:", bheap.get_max())
  100.                 elif sub == "extract":
  101.                     print("Maximum value removed:", bheap.extract_max())
  102.                 else:
  103.                     print("Invalid max command.")
  104.  
  105.         elif operation == "display":
  106.             bheap.display()
  107.  
  108.         elif operation == "quit":
  109.             break
  110.  
  111.         else:
  112.             print("Invalid command.")
  113.  
  114.     # Try again option
  115.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  116.     if opt == "no":
  117.         print("Exiting program...")
  118.         break
  119.     elif opt != "yes":
  120.         print("Invalid choice. Exiting program...")
  121.         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

Python Tutorials