[Numpy-discussion] k maximal elements

gary ruben gruben at bigpond.net.au
Mon Jun 6 09:57:55 EDT 2011


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)

On Mon, Jun 6, 2011 at 10:52 PM, Olivier Delalleau <shish at keba.be> wrote:
> I don't really understand your proposed solution, but you can do something
> like:
>
> import heapq
> q = list(x)
> heapq.heapify(q)
> k_smallest = [heapq.heappop(q) for i in xrange(k)]
>
> which is in O(n + k log n)
>
> -=- Olivier
>
> 2011/6/6 Alex Ter-Sarkissov <ater1980 at gmail.com>
>>
>> I have a vector of positive integers length n. Is there a simple (i.e.
>> without sorting/ranking) of 'pulling out' k larrgest (or smallest) values.
>> Something like
>>
>> sum(x[sum(x,1)>(max(sum(x,1)+min(sum(x,1))))/2,])
>>
>> but smarter
>>
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion at scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>>
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>



More information about the NumPy-Discussion mailing list