nathanwailes

Heapq

Jun 9th, 2024
520
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. """
  2. """
  3. import heapq
  4.  
  5. # Creating a heap
  6. heap = []
  7.  
  8. # Adding elements to the heap
  9. heapq.heappush(heap, 3)  # Add element 3 to the heap
  10. heapq.heappush(heap, 1)  # Add element 1 to the heap
  11. heapq.heappush(heap, 4)  # Add element 4 to the heap
  12. heapq.heappush(heap, 2)  # Add element 2 to the heap
  13.  
  14. # Accessing the smallest element without popping it
  15. smallest_element = heap[0]
  16.  
  17. # Removing the smallest element from the heap
  18. smallest = heapq.heappop(heap)  # Remove and return the smallest element
  19.  
  20. # Pushing and popping an element in one operation
  21. pushpop_result = heapq.heappushpop(heap, 5)  # Push 5 and pop the smallest element
  22.  
  23. # Replacing the smallest element with a new element
  24. replace_result = heapq.heapreplace(heap, 6)  # Replace and return the smallest element with 6
  25.  
  26. # Converting a list into a heap
  27. data = [5, 7, 9, 1, 3]
  28. heapq.heapify(data)  # Transform list into a heap
  29.  
  30. # Finding the n largest elements
  31. largest_elements = heapq.nlargest(3, data)  # Find the 3 largest elements
  32.  
  33. # Finding the n smallest elements
  34. smallest_elements = heapq.nsmallest(3, data)  # Find the 3 smallest elements
  35.  
  36. # Merging multiple sorted inputs into a single sorted output
  37. merged = list(heapq.merge([1, 3, 5], [2, 4, 6]))  # Merge sorted inputs
  38.  
Advertisement
Add Comment
Please, Sign In to add comment