Nlargest element in list

Viewed 878

Is there is anyway to compute N Largest element in a list without foor loop?

def Nlargest(list):
     #your code here
     #print n largest element of a list without for loop
3 Answers
def Nlargest(list):
    import heapq
   print(heapq.nlargest(n,list))  #return a list of n largest element 

I hope this would help you

If you care about performance, you can find an implementation of the Quick-Select algorithm. It runs in linear runtime, opposed to n log n for algorithms which rely on sorting.

If runtime isn't important, you can take one of the suggestion in the comments.

You can sort the list and print the last n elemets(largest n elements in the list) as follows

def Nlargest(list):
    list.sort()        # first sort the list
    print(list[-n:])   # print the last n elements as they will be the largest ones

A short hand for the code (which doesn't mutate the original list) above would be -

def Nlargest(list):
    print(sorted(list, reverse=True)[:n]) #sort in descending order and print first n elements

Hope this helps !

Related