Python program to find Nth largest element in a list

Python program to find Nth largest element in a list

Problem description :

The program gets a list of numbers and n as input and returns nth greatest element in the list.

For example, 

Consider the list L1 = [5, 6, 1 3, 8, 4, 9] and N=3, so the result will be the third  greatest element = 6.

Consider another list L2 = [0, 3, 1, 7, 5, 8, 4, 9] and N = 2, here the output will be the second greatest element  = 8.

Procedure :

1. Start.

2. Get the elements of the list separated by space as input from user.

3. Get n as input from the user.

4. Sort the list.

5. Nth greatest element =  len(l)-n th element in the sorted list.

6. Print the nth greatest element.

7. End.

Code :

#get the elements of the list separated by space

l = list(map(int,input("Enter the elements of the list separated by space : ").split()))

#get the number, n from user

n = int(input("Enter n : "))

#sort the list

l.sort()

#find the nth greatest element in the list

max_elt = l[len(l)-n]

#print the nth greatest element in the list

print("The nth greatest element (n=", n ,") is ", max_elt)

Sample input 0 :

l = [7, 1, 2, 9, 0, 4]

n = 4

Sample output 0 :

The 4th greatest element is 2.

Sample input 1 :

l = [3, 4, 1, 2, 6, 5, 9]

n = 3

Sample output 1 :

The 3rd greatest element is 5.

Output screenshot :

Nth largest element in python



Nth largest element in python






Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

ginortS in Python - HackerRank solution