Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 finding 2 max values in an array in python
(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.
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)]

>>> heapq.nlargest(2, [(v, i) for i, v in enumerate(lst)])
>>> [(42, 8), (37, 9)]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Finding an element in a 1d list in a 2d array lionrocker221 0 200 Jun-27-2020, 04:50 PM
Last Post: lionrocker221
  Finding Max and Min Values Associated with Unique Identifiers in Python ubk046 1 145 May-08-2020, 12:04 PM
Last Post: anbu23
  change array column values without loop khalidreemy 2 481 May-05-2019, 09:05 AM
Last Post: DeaD_EyE
  Spyder hides middle array values in variable explorer window davidqvist 0 741 Aug-03-2018, 11:04 AM
Last Post: davidqvist
  Need help for finding cumulative values in a loop Lightning1800 10 1,933 May-23-2018, 07:48 PM
Last Post: Lightning1800
  Finding all maximum values in a matrix Lightning1800 3 1,240 May-14-2018, 03:55 PM
Last Post: Lightning1800
  Finding values to draw a line on a curve kesenthilkumar 2 1,389 Sep-19-2017, 09:50 AM
Last Post: kesenthilkumar
  Extract values from array mehtamonita 8 4,460 Apr-18-2017, 02:45 PM
Last Post: mehtamonita

Forum Jump:

Users browsing this thread: 1 Guest(s)