Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- """
- import heapq
- # Creating a heap
- heap = []
- # Adding elements to the heap
- heapq.heappush(heap, 3) # Add element 3 to the heap
- heapq.heappush(heap, 1) # Add element 1 to the heap
- heapq.heappush(heap, 4) # Add element 4 to the heap
- heapq.heappush(heap, 2) # Add element 2 to the heap
- # Accessing the smallest element without popping it
- smallest_element = heap[0]
- # Removing the smallest element from the heap
- smallest = heapq.heappop(heap) # Remove and return the smallest element
- # Pushing and popping an element in one operation
- pushpop_result = heapq.heappushpop(heap, 5) # Push 5 and pop the smallest element
- # Replacing the smallest element with a new element
- replace_result = heapq.heapreplace(heap, 6) # Replace and return the smallest element with 6
- # Converting a list into a heap
- data = [5, 7, 9, 1, 3]
- heapq.heapify(data) # Transform list into a heap
- # Finding the n largest elements
- largest_elements = heapq.nlargest(3, data) # Find the 3 largest elements
- # Finding the n smallest elements
- smallest_elements = heapq.nsmallest(3, data) # Find the 3 smallest elements
- # Merging multiple sorted inputs into a single sorted output
- merged = list(heapq.merge([1, 3, 5], [2, 4, 6])) # Merge sorted inputs
Advertisement
Add Comment
Please, Sign In to add comment