Find K’th largest element in a stream in Python

In this tutorial, you will learn how to find the K’th largest element in a stream in Python.

First, understand the question. We have a stream of numbers like “1,5,3,10,23,45,9” then the 3 rd largest element is 10. Because, if we arrange the stream in descending order then it’s like “45,23,10,9,5,3,1 “. Now, we can easily say that 45 is 1st, 23 is 2nd and 10 is the 3rd largest number.

See how can make a Python code of this problem……….

Code of Kth_Largest()

def Kth_Largest(k,stream):
    
    try:
        List = list(map(int,stream.split(',')))
        List.sort()
        if k > len(List)  or k <= 0:
            print('Value of K is:  0 < K < ',len(List)+1,"  for this stream",sep="")
            
        else:
            print(k,'th Largest number of this stream is: ',List[-k],sep="")
    except:
        print(" Sorry! you didn't maintain the input stream format. \n Input stream format is like "'"1,3,6,10,23"'" (use , between two numbers).")

 

Kth_Largest(4,”3,45,23,9,97,12,5″)

Output:
4th Largest number of this stream is: 12

Let’s understand the code

  1. The def function contained two arguments 1st for the value of K and 2nd for the stream.
  2. try and except function are used because if someone inputs the stream in a wrong format then the code won’t show the Error but it shows the guideline of the stream formate.
    Ex….
    Kth_Largest(4, “3 45 23 9 97 12 5”)

    Output:
    
    Sorry you didn't maintain the input stream format 
    
    Input stream format is like "1,3,6,10,23" (use , between two numbers)

    This code shows the guidelines instead of Error event the input stream format is wrong because of try and except functions.

  3. list(map(int,stream.split(‘,’)) is used to split the stream from every ” , ” and transform into the list.
  4. if and else statements are used to restrict the value of K. Because K value is:  0 < K < (len(List) +1).

Leave a Reply