Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Request for argmax(list) and argmin(list)

41 views
Skip to first unread message

ABCCDE921

unread,
Sep 1, 2021, 12:25:26 AM9/1/21
to
I dont want to import numpy

argmax(list)
returns index of (left most) max element

argmin(list)
returns index of (left most) min element

Paul Rubin

unread,
Sep 1, 2021, 12:33:42 AM9/1/21
to
ABCCDE921 <atharvasa...@gmail.com> writes:
> argmax(list)
> returns index of (left most) max element

Does this work?

def argmax(lst):
i,x = max(enumerate(xs), key=lambda a: a[1])
return i

Paul Bryan

unread,
Sep 1, 2021, 2:32:29 AM9/1/21
to
Why not:

>>> l = [1, 3, 5, 9, 2, 7]
>>> l.index(max(l))
3
>>> l.index(min(l))
0

ABCCDE921

unread,
Sep 1, 2021, 3:20:29 AM9/1/21
to
Because that does 2 passes over the entire array when you only need one and there is no option to specify if you want the leftmost or rightmost element

Peter Otten

unread,
Sep 1, 2021, 3:36:51 AM9/1/21
to
On 01/09/2021 06:25, ABCCDE921 wrote:
> I dont want to import numpy
>
> argmax(list)
> returns index of (left most) max element


>>> import operator
>>> second = operator.itemgetter(1)
>>> def argmax(values):
return max(enumerate(values), key=second)[0]

>>> argmax([1, 2, 3, 0])
2

> argmin(list)
> returns index of (left most) min element

This is left as an exercise;)



Calvin Spealman

unread,
Sep 1, 2021, 10:47:11 AM9/1/21
to
If only there were a library that already provides exactly the functions
you're asking for... 🤔

On Wed, Sep 1, 2021 at 9:54 AM ABCCDE921 <atharvasa...@gmail.com>
wrote:
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>

--

CALVIN SPEALMAN

SENIOR QUALITY ENGINEER

calvin....@redhat.com M: +1.336.210.5107
[image: https://red.ht/sig] <https://red.ht/sig>
TRIED. TESTED. TRUSTED. <https://redhat.com/trusted>

Dan Stromberg

unread,
Sep 2, 2021, 6:15:06 PM9/2/21
to
How about this?:

python3 -c 'list_ = [1, 3, 5, 4, 2]; am = max((value, index) for index,
value in enumerate(list_)); print(am)'


On Wed, Sep 1, 2021 at 6:51 AM ABCCDE921 <atharvasa...@gmail.com>
wrote:
> --
> https://mail.python.org/mailman/listinfo/python-list
>
0 new messages