suppose you were asked to write program which takes sequence of strings presented in "streamingfashionyou cannot back up to read an earlier value your program must compute the longest strings in the sequence all that is required is the longest strings--it is not required to order these strings as we process the inputwe want to track the longest strings seen so far out of these stringsthe string to be evicted when longer string is to be added is the shortest one min-heap (not max-heap!is the right data structure for this applicationsince it supports efficient find-minremove-minand insert in the program below we use heap with custom compare functionwherein strings are ordered by length def top_k (kstream )entries are compared by their lengths min_heap [len( )sfor in itertools islice (stream )heapq heapify min_heap for next_string in stream push next_string and pop the shortest string in min_heap heapq heappushpop (min_heap (lennext_string )next_string )return [ [ for in heapq nsmallest (kmin_heap )each string is processed in (log ktimewhich is the time to add and to remove the minimum element from the heap thereforeif there are strings in the inputthe time complexity to process all of them is ( log kwe could improve best-case time complexity by first comparing the new string' length with the length of the string at the top of the heap (getting this string takes ( timeand skipping the insert if the new string is too short to be in the set use heap when all you care about is the largest or smallest elementsand you do not need to support fast lookupdeleteor search operations for arbitrary elements heap is good choice when you need to compute the largest or smallest elements in collection for the formeruse min-heapfor the latteruse max-heap table top tips for heaps know your heap libraries heap functionality in python is provided by the heapq module the operations and functions we will use are heapq heapify( )which transforms the elements in into heap in-placeheapq nlargest(kl(heapq nsmallest(kl)returns the largest (smallestelements in lheapq heappush(he)which pushes new element on the heapheapq heappop( )which pops the smallest element from the heapheapq heappushpop(ha)which pushes on the heap and then pops and returns the smallest elementand [ ]which returns the smallest element on the heap without popping it it' very important to remember that heapq only provides min-heap functionality if you need to build max-heap on integers or floatsinsert their negative to get the effect of max-heap using heapq for objectsimplement __lt()__ appropriately