def nlargest(n, iterable, key=None):
 if (n == 1):
  it = iter(iterable)
  head = list(islice(it, 1))
  if (not head):
   return []
  if (key is None):
   return [max(chain(head, it))]
  return [max(chain(head, it), key=key)]
 try:
  size = len(iterable)
 except (TypeError, AttributeError):
  pass
 else:
  if (n >= size):
   return sorted(iterable, key=key, reverse=True)[:n]
 if (key is None):
  it = izip(iterable, imap(neg, count()))
  result = _nlargest(n, it)
  return map(itemgetter(0), result)
 (in1, in2) = tee(iterable)
 it = izip(imap(key, in1), imap(neg, count()), in2)
 result = _nlargest(n, it)
 return map(itemgetter(2), result)

def nlargest ( n , iterable , key = None ) : if ( n == 1 ) : it = iter ( iterable ) head = list ( islice ( it , 1 ) ) if ( not head ) : return [ ] if ( key is None ) : return [ max ( chain ( head , it ) ) ] return [ max ( chain ( head , it ) , key = key ) ] try : size = len ( iterable ) except ( TypeError , AttributeError ) : pass else : if ( n >= size ) : return sorted ( iterable , key = key , reverse = True ) [ : n ] if ( key is None ) : it = izip ( iterable , imap ( neg , count ( ) ) ) result = _nlargest ( n , it ) return map ( itemgetter ( 0 ) , result ) ( in1 , in2 ) = tee ( iterable ) it = izip ( imap ( key , in1 ) , imap ( neg , count ( ) ) , in2 ) result = _nlargest ( n , it ) return map ( itemgetter ( 2 ) , result )
find the n largest elements in a dataset .