How to Implement Ternary Heap in Python

In this tutorial, we will learn how to program “How to Implement a Ternary Heap in Python.” The main objective is to implement a ternary heap data structure. This tutorial will guide you step by step through the process of implementing a ternary heap. By the end of this tutorial, you will have a solid understanding of how ternary heaps work in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

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 implementing a ternary heap. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of data structures in Python.

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

This program demonstrates the implementation of a Ternary Heap, a variation of the heap data structure in which each parent node can have up to three children instead of two. The `TernaryHeap` class manages the heap using a list and provides functions to determine the parent and the three child positions (left, middle, and right). It maintains the max-heap property, where the value of each parent node is greater than or equal to the values of its children. The program allows users to insert elements into the heap, retrieve the maximum value without removing it, and extract the maximum value while reorganizing the heap using the `max_heapify` method to preserve the heap structure. Through a menu-driven interface, users can repeatedly perform these operations, making the program a practical example of how ternary heaps work and how they extend the concept of binary heaps by allowing three children per node.

Output:

There you have it we successfully created How to Implement Ternary 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