Tough sorting problem: or, I'm confusing myself

Raymond Hettinger python at
Wed Apr 14 12:06:13 EDT 2010

> I'm not sure a heap will help much, and at least to me,
> doesn't improve readability.

nlargest() should save quite a few comparisons and run much faster
than sorted().

Not sure what the readability issue is.  The phrase "nlargest(2,
iterable)" does exactly what it says, finds the 2 largest elements
from an iterable.  That makes the programmer's intent more clear than
the slower, but semanticly equivalent form:  sorted(iterable)[:2].

The running time for your algorithm can be very long, depending on the
inputs.  Do you need an exact answer or can you approximate it with
sampling random combinations (i.e. choose the best two scores out of
10000 samples).


More information about the Python-list mailing list