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
2010-06-01 01:55:01
@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
2010-06-01 02:10:20