argmax

Peter Otten __peter__ at web.de
Thu Jun 1 12:03:47 EDT 2006


David Isaac wrote:

> 2. Is this a good argmax (as long as I know the iterable is finite)?
> def argmax(iterable): return max(izip( iterable, count() ))[1]

There's a subtle difference to the builtin: argmax() gives you the (index of
the) last maximum while max() returns the (value of the) first maximum:

>>> from itertools import count, izip
>>> def argmax(iterable):
...     return max(izip(iterable, count()))[1]
...
>>> class Int(int): pass
...
>>> type(max([Int(0), 0]))
<class '__main__.Int'> # must be the first item then
>>> argmax([Int(0), 0])
1

If you care, here's the fix building on George's implementation:

>>> def argmax2(iterable):
...     return -max((v, -i) for i, v in enumerate(iterable))[1]
...
>>> argmax2([Int(0), 0])
0

Peter



More information about the Python-list mailing list