[Python-Dev] argmax?

Josiah Carlson jcarlson at uci.edu
Thu Jan 8 12:59:14 EST 2004


Miki,

That sounds quite a bit like:

from itertools import imap, izip

argmax = lambda funct, items: max(izip(imap(funct, items), items))
argmin = lambda funct, items: min(izip(imap(funct, items), items))

Which breaks ties on vals using a comparison with items (I don't know if
this is desireable to you).

Running a quick test on large sequences (range(100000)) with a
relatively simple function (lambda a:a*a) produces the following timings
on my machine (best of 7):
argmax: 5.953 seconds (with std. dev. of .01455 seconds)
izipimap: 5.844 seconds (with std. dev. of .03009 seconds)
zipmap: 6.407 seconds (with std. dev. of .072356 seconds)

Seems to be a small win for itertools, a close second for your original argmax,
and a harrowing loss for map and zip on large sequences.


I don't know how anyone would feel about adding it to the standard
library,
 - Josiah


> Do you think there is a place for an "argmax" function (which I use a lot)
> in the standard library?
> 
> I'm thinking in the lines of:
> 
> def argmax(items, func, cmp=cmp):
>     '''argmax(items, func) -> max_item, max_value'''
>     it = iter(items)
>     # Initial values
>     try:
>         item = it.next()
>     except StopIteration:
>         raise ValueError("can't run over empty sequence")
>     val = func(item)
> 
>     for i in it:
>         v = func(i)
>         if cmp(v, val) == 1:
>             item = i
>             val = v
>     return item, val
> 
> def argmin(items, func, cmp=cmp):
>     '''argmin(items, func) -> min_item, min_value'''
>     return argmax(items, func, lambda x,y : -cmp(x,y))




More information about the Python-Dev mailing list