Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the 2nd highest element

Tags:

python

  1. In a given array how to find the 2nd, 3rd, 4th, or 5th values?

  2. Also if we use themax() function in python what is the order of complexity i.e, associated with this function max()?

.

def nth_largest(li,n):   
    li.remove(max(li))
    print max(ele)  //will give me the second largest
    #how to make a general algorithm to find the 2nd,3rd,4th highest value
    #n is the element to be found  below the highest value
like image 272
Hulk Avatar asked Aug 31 '13 15:08

Hulk


1 Answers

I'd go for:

import heapq
res = heapq.nlargest(2, some_sequence)
print res[1] # to get 2nd largest

This is more efficient than sorting the entire list, then taking the first n many elements. See the heapq documentation for further info.

like image 166
Jon Clements Avatar answered Oct 18 '22 11:10

Jon Clements