argmax
Ben Cartwright
bencvt at gmail.com
Thu Jun 1 18:33:38 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]
Other than the subtle difference that Peter Otten pointed out, that's a
good method.
However if the iterable is a list, it's cleaner (and more efficient) to
use seq.index(max(seq)). That way you won't be creating and comparing
all those tuples.
def argmax(it):
try:
it.index
except AttributeError:
it = list(it)
# Or if it would too expensive to convert it to list:
#return -max((v, -i) for i, v in enumerate(it))[1]
return it.index(max(it))
--Ben
More information about the Python-list
mailing list