Question: class TopKHeap: # The constructor of the class to initialize an empty data structure def _ _ init _ _ ( self , k )
class TopKHeap:
# The constructor of the class to initialize an empty data structure
def initself k:
self.k k
self.A
self.H MinHeap
def sizeself:
return lenselfAselfHsize
def getjthelementself j:
assert j self.k
assert j self.size
return self.Aj
def satisfiesassertionsself:
# is self.A sorted
for i in rangelenselfA:
assert self.Ai self.Ai f'Array A fails to be sorted at position iselfAi self.Ai
# is self.H a heap check minheap property
self.Hsatisfiesassertions
# is every element of self.A less than or equal to each element of self.H
for i in rangelenselfA:
assert self.Ai self.Hminelement f'Array element AiselfAi is larger than min heap element selfHminelement
# Function : insertintoA
# This is a helper function that inserts an element elt into selfA
# whenever size is k
# append elt to the end of the array A
# Move the element that you just added at the very end of
# array A out into its proper place so that the array A is sorted.
# return the "displaced last element" jHat None if no element was displaced
def insertintoAself elt:
printk self.k
assertselfsize self.k
self.Aappendelt
j lenselfA
while j and self.Aj self.Aj:
# Swap Aj and Aj
selfAj self.AjselfAj self.Aj
j j
return
# Function: insert insert an element into the data structure.
# Code to handle when self.size self.k is already provided
def insertself elt:
size self.size
# If we have fewer than k elements, handle that in a special manner
if size self.k:
self.insertintoAelt
return
# Code up your algorithm here.
# your code here
# Function: Delete top k delete an element from the array A
# In particular delete the jth element where j means the least element.
# j must be in range to self.k
def deletetopkself j:
k self.k
assert self.size k # we need not handle the case when size is less than or equal to k
assert j
assert j self.k
# your code here
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
