tags:

views:

172

answers:

2

I can't edit or sort the list. How can I get that index?

A: 

What you've got is already O(n) in complexity (max is O(n), as is index(), IIRC). So while you could technically just remove the largest if it's not appropriate and try again, you're starting to get into bubblesort territory in terms of big-O. How many items are typically on the list?

One option is QuickSelect, which is basically a reduced QuickSort, but honestly just sorting the list up front is not going to be much slower than what you've got already.

You can use the sorted() function to return a new sorted list if you don't want to change the ordering of the original list.

Dean Harding
@Jim Lewis: yes, that's why I pointed to QuickSelect, which is O(n). I didn't actually know python had an nlargest function already, which sth pointed out... shows my newbness with python :) My point was (if nlargest didn't exist), sorting the list (O(nlogn)) is not going to be much worse than the 2xO(n) that he was already doing...
Dean Harding
+2  A: 

The heapq module provides a nlargest function that efficiently finds the n largest elements of a list:

>>> from heapq import nlargest
>>> items = [100, 300, 200, 400]
>>> indexes = [0, 1, 2, 3]
>>> nlargest(2, indexes, key=lambda i: items[i])
[3, 1]
sth
thats all i wanted to read
Daniel
thank you very much =D
Daniel