[Numpy-discussion] k maximal elements

Keith Goodman kwgoodman@gmail....
Mon Jun 6 09:06:51 CDT 2011


On Mon, Jun 6, 2011 at 6:57 AM, gary ruben <gruben@bigpond.net.au> wrote:
> I learn a lot by watching the numpy and scipy lists (today Olivier
> taught me about heapq :), but he may not have noticed that Python 2.4
> added an nsmallest method)
>
> import heapq
> q = list(x)
> heapq.heapify(q)
> k_smallest = heapq.nsmallest(k,q)

I learned something new too---heapq.

Timings:

    >> alist = a.tolist()
    >> heapq.heapify(alist)
    >> timeit k_smallest = heapq.nsmallest(k, alist)
    100 loops, best of 3: 1.84 ms per loop
    >> timeit bn.partsort(a, a.size-10)
    10000 loops, best of 3: 39.3 us per loop


More information about the NumPy-Discussion mailing list