Alex Rivera | Logout

Python: take max N elements from some list

Asked 2010-11-18T13:54:56.453
41

Is there some function which would return me the N highest elements from some list?

I.e. if max(l) returns the single highest element, sth. like max(l, count=10) would return me a list of the 10 highest numbers (or less if l is smaller).

Or what would be an efficient easy way to get these? (Except the obvious canonical implementation; also, no such things which involve sorting the whole list first because that would be inefficient compared to the canonical solution.)

Edit
Report

1 Answer

3

Start with the first 10 from L, call that X. Note the minimum value of X.

Loop over L[i] for i over the rest of L.

If L[i] is greater than min(X), drop min(X) from X and insert L[i]. You may need to keep X as a sorted linked list and do an insertion. Update min(X).

At the end, you have the 10 largest values in X.

I suspect that will be O(kN) (where k is 10 here) since insertion sort is linear. Might be what gsl uses, so if you can read some C code:

http://www.gnu.org/software/gsl/manual/html_node/Selecting-the-k-smallest-or-largest-elements.html

Probably something in numpy that does this.

answered 2010-11-18T14:11:09.547

Your Answer