nathanwailes

Heap

Apr 5th, 2024
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. """
  2. A heap is a specialized tree-based data structure that satisfies the heap property. In a heap, for any given node C, if P is a parent node of C, then the key (the value) of node P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of node C. The node at the "top" of the heap (with no parents) is called the root node.
  3.  
  4. Types of Heaps
  5. - Max Heap: In a max heap, for any given node C and parent node P, the key of P is greater than or equal to the key of C. Thus, the node with the greatest key is always the root node of the tree.
  6. - Min Heap: In a min heap, for any given node C and parent node P, the key of P is less than or equal to the key of C. Thus, the node with the smallest key is always the root node of the tree.
  7.  
  8. In Python, the heapq module provides an implementation of the min heap. By default, heapq creates a min heap, where the smallest element is always popped first. Here's a quick overview of some of the functions provided by the heapq module:
  9.  
  10. - heapq.heappush(heap, item): Pushes a new item onto the heap, maintaining the heap invariant.
  11. - heapq.heappop(heap): Pops and returns the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised.
  12. - heapq.heapify(x): Transforms the list x into a heap in linear time.
  13. """
  14.  
  15. import heapq
  16.  
  17. def heap(nums, k):
  18.     # Initialize a min heap
  19.     min_heap = nums[:k]
  20.     heapq.heapify(min_heap)
  21.    
  22.     # Iterate through the rest of nums
  23.     for num in nums[k:]:
  24.         if num > min_heap[0]:  # If current num is larger than the smallest in heap
  25.             heapq.heappop(min_heap)  # Remove the smallest
  26.             heapq.heappush(min_heap, num)  # Push the current num
  27.            
  28.     # The heap contains the k largest elements
  29.     return min_heap
  30.  
  31. # Example usage
  32. nums = [3, 2, 3, 1, 2, 4, 5, 5, 6]
  33. k = 4
  34. print(heap(nums, k))
  35. # Output: [4, 5, 5, 6]
  36.  
Advertisement
Add Comment
Please, Sign In to add comment