In Python, a heap is a binary tree-based data structure that satisfies the heap property, meaning that the parent node is less than or equal to any of its child nodes in a min-heap or greater than or equal to any of its child nodes in a max-heap. This property allows heaps to efficiently support operations like finding the minimum or maximum element.
Python provides a heapq module that implements a min-heap on top of a regular list with functions that maintain the heap property while elements are added or removed. Here's how to use it:
- Creating a Heap:
You can create a heap by initializing an empty list or by using the
heapify function to convert an iterable into a heap.
import heapq
# Starting with an empty heap
heap = []
# Starting with an existing list of elements and turning it into a heap
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
heapq.heapify(data) # The list 'data' is now a heap
- Adding Elements:
Use the
heappush function to add elements to the heap while maintaining the heap property.
heapq.heappush(heap, item) # Adds 'item' to the heap
- Removing Elements:
Use the
heappop function to remove and return the smallest element from the heap, ensuring the heap property is maintained after the removal.
smallest = heapq.heappop(heap) # Removes and returns the smallest element
- Accessing the Smallest Element:
The smallest element in the heap can be accessed directly as the first element of the list without removing it.
smallest = heap[0] # Gets the smallest element without removing it
- Replacing Elements:
If you need to pop the smallest element and push a new item, you can use
heapreplace to do both operations more efficiently.
heapq.heapreplace(heap, item) # Pops and returns smallest, then adds 'item'
- Converting a Min-Heap to a Max-Heap:
The
heapq module only provides a min-heap implementation. To use it as a max-heap, you can insert tuples with the first element being the negative of the value or use a custom key function.
# Using a max-heap with negative values
max_heap = []
for item in data:
heapq.heappush(max_heap, -item)
# Now, to get the maximum value, you pop and negate the value
largest = -heapq.heappop(max_heap)
- Other Useful Functions:
nlargest: To get a list of the n largest elements from a dataset.
nsmallest: To get a list of the n smallest elements from a dataset.
merge: To merge multiple sorted inputs into a single sorted output (returns an iterator).
largest_three = heapq.nlargest(3, data) # Gets the three largest elements
smallest_three = heapq.nsmallest(3, data) # Gets the three smallest elements
# Merging sorted sequences
for element in heapq.merge([1, 3, 5], [2, 4, 6]):
print(element, end=' ') # Output: 1 2 3 4 5 6
Keep in mind that heapq operates on lists and assumes that the list will be maintained as a heap at all times (i.e., you should not manually reorder items in the list). Always use heapq functions to manipulate the heap to preserve the heap properties.