Python Forum
finding 2 max values in an array in python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: finding 2 max values in an array in python (/thread-13441.html)

Pages: 1 2


RE: finding 2 max values in an array in python - nilamo - Oct-17-2018

(Oct-17-2018, 09:43 PM)LeSchakal Wrote: I was afraid of this a little bit, but never thought it would happen so early.
tbh it's probably fine. Use whatever makes sense to you, so you can easily understand it the next time you look at it. And once your program is noticeably slow, profile it and improve the bottlenecks.


RE: finding 2 max values in an array in python - perfringo - Oct-18-2018

There is also heapq for finding nlargest and nsmallest values.

From Python Cookbook, 3rd Edition by David Beazley; Brian K. Jones, O'Reilly Media 2013:

Quote:The nlargest() and nsmallest() functions are most appropriate if you are trying to find a relatively small number of items. If you are simply trying to find the single smallest or largest item (N=1), it is faster to use min() and max(). Similarly, if N is about the same size as the collection itself, it is usually faster to sort it first and take a slice (i.e., use sorted(items)[:N] or sorted(items)[-N:]). It should be noted that the actual implementation of nlargest() and nsmallest() is adaptive in how it operates and will carry out some of these optimizations on your behalf (e.g., using sorting if N is close to the same size as the input).

Borrowing nilamo's lambda it can be expressed:

>>> import heapq
>>> lst = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> heapq.nlargest(2, enumerate(lst), key=lambda x: x[1])
[(8, 42), (9, 37)]
Or:

>>> heapq.nlargest(2, [(v, i) for i, v in enumerate(lst)])
>>> [(42, 8), (37, 9)]