[Python-Dev] argmax?

Miki Tebeka miki.tebeka at zoran.com
Thu Jan 8 04:08:56 EST 2004


Hello All,

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))

Thanks.
--
-----------------------------------------------------------
Smile, damn it, smile.

lambda msg: {
        "name" : "Miki Tebeka",
        "email" : "miki.tebeka at zoran.com",
        "url" : "http://www.cs.bgu.ac.il/~tebeka",
        "quote" : "The only difference between children and adults " \
                  "is the price of the toys"
}[msg]



More information about the Python-Dev mailing list