import heapq class KthLargest: # Constructor to initialize heap and add values in it def __init__(self, k, nums): print("\tInitializing the heap") self.top_k_heap = [] self.k = k print("\tk =", self.k) print("\tHeap: ", self.top_k_heap) for element in nums: print("\tAdding element", element, "to the heap.") self.add(element) # Adds element in the heap and return the Kth largest def add(self, val): if len(self.top_k_heap) < self.k: print("\tSize of the heap is less than k, so we’ll push", val) heapq.heappush(self.top_k_heap, val) elif val > self.top_k_heap[0]: print("\tSize of the heap is equal to k and", val, "is greater than the top of heap", self.top_k_heap[0]) print("\tWe will pop the top element from heap and push the new element.") heapq.heappop(self.top_k_heap) heapq.heappush(self.top_k_heap, val) else: print("\tSize of the heap is equal to k and", val, "is equal to or smaller than the top of heap.") print("\tNo operation will be performed.") print("\tHeap:", self.top_k_heap) return self.top_k_heap[0] # Driver code def main(): nums = [3, 6, 9, 10] temp = [3, 6, 9, 10] print("Initial stream: ", nums, sep = "") k_largest = KthLargest(3, nums) val = [4, 7, 10, 8, 15] for i in range(len(val)): print("\tAdding a new number ", val[i], " to the stream", sep = "") temp.append(val[i]) print("\tNumber stream: ", temp, sep = "") print("\tKth largest element in the stream: ", k_largest.add(val[i])) print("-"*100) if __name__ == "__main__": main()