HEAP IN PYTHON MADE EASY
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]
- The first line imports the
heapq
library in Python. This library provides functions to work with heaps - The second line creates a list called
heap
with elements [3, 2, 1]. - The third line calls the
heapify
function from theheapq
library, which converts the listheap
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. - The fourth line prints the list
heap
after it has been converted into a min-heap. The output will be[1, 2, 3]
. - The fifth line calls the
heappush
function from theheapq
library, which pushes the value 4 onto the min-heapheap
. The function automatically adjusts the min-heap so that the min-heap property is maintained. - The sixth line calls the
heappop
function from theheapq
library, which pops and returns the smallest value from the min-heapheap
. - 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:
- 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.
- Sorting: The heap sort algorithm uses a binary heap to sort an array of elements.
- 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.