Find n largest/ smallest item in a list

Using python built-in heapq functions:

def find_nsmallest( seq, n):
    import heapq
    return heapq.nsmallest( n, seq)

def find_nlargest( seq, n):
    import heapq
    return heapq.nlargest( n, seq)

Recursive-definition:

def nlargest( seq, n):
    pivot= seq[0]
    below= [s for s in seq if s < pivot]
    above= [s for s in seq if s > pivot]
    i,j= len( below), len( seq) - len(above)
    
    if n < i: return nlargest( below, n)
    elif n >= j: return nlargest( above, n-j)
    else: return pivot

Leave a comment