HEAP IN PYTHON MADE EASY

Nkugwa Mark William
2 min readFeb 5, 2023

--

heap is an essential concept in computer science, and is related to memory management and the way that data is stored and accessed in a program.

Heap, is a data structure that follows the Complete Binary Tree property, which means that the parent node is either greater than or equal to its children (Max Heap) or less than or equal to its children (Min Heap). To implement a heap in Python, you can use the heapq module, which provides functions for creating and manipulating heaps.

For example:

import heapq
heap = [3, 2, 1]
heapq.heapify(heap)
print(heap) # Output: [1, 2, 3]
heapq.heappush(heap, 4)
print(heap) # Output: [1, 2, 3, 4]
heapq.heappop(heap)
print(heap) # Output: [2, 4, 3]
  1. The first line imports the heapq library in Python. This library provides functions to work with heaps
  2. The second line creates a list called heap with elements [3, 2, 1].
  3. The third line calls the heapify function from the heapq library, which converts the list heap into a valid min-heap. A min-heap is a complete binary tree where the value of each node is less than or equal to the values of its children.
  4. The fourth line prints the list heap after it has been converted into a min-heap. The output will be [1, 2, 3].
  5. The fifth line calls the heappush function from the heapq library, which pushes the value 4 onto the min-heap heap. The function automatically adjusts the min-heap so that the min-heap property is maintained.
  6. The sixth line calls the heappop function from the heapq library, which pops and returns the smallest value from the min-heap heap.
  7. The seventh line prints the updated min-heap after the heappop function has been called. The output will be [2, 4, 3].

You would use a heap when you need to maintain a priority order of elements. Heaps are commonly used in computer programming for a variety of purposes, including:

  1. Priority Queues: Heaps can be used to implement priority queues, where elements are ordered based on their priority and retrieved in the order of their priority.
  2. Sorting: The heap sort algorithm uses a binary heap to sort an array of elements.
  3. Graph algorithms: Heaps are used in several graph algorithms, such as Dijkstra’s shortest path algorithm and the A* search algorithm, to keep track of the most promising vertices to visit next.

--

--

Nkugwa Mark William
Nkugwa Mark William

Written by Nkugwa Mark William

Nkugwa Mark William is a Chemical and Process engineer , entrepreneur, software engineer and a technologists with Apps on google play store and e commerce sites

No responses yet