On Thu, 22 Apr 2010 10:49:29 -0700, John Nagle wrote:
> Is "nlargest" smart enough to decide when it's cheaper to track the
> N largest entries on a linear pass through the list than to sort?
Doesn't appear to do so. From Python 3.1:
def nlargest(n, iterable):
"""Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, reverse=True)[:n]
"""
it = iter(iterable)
result = list(islice(it, n))
if not result:
return result
heapify(result)
_heappushpop = heappushpop
for elem in it:
_heappushpop(result, elem)
result.sort(reverse=True)
return result
although if there is a C implementation, Python will use that instead of
the above, and that may be different.
Interestingly, nsmallest does use two different algorithms, depending on
how many items you ask for. See the source code.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list