[Tutor] max min value in array

Rich Lovely roadierich at googlemail.com
Thu Sep 17 14:06:23 CEST 2009

2009/9/17 Rayon <evosweet at hotmail.com>:
> I need to find the max and min value from some floats in a array:
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Depending on the size of the array, there's two methods:  Using the
max and min builtin functions, which will be faster for small arrays,
or hand-coding a single pass function, which might be faster for
arrays above a certain size.

def minmax1(a):
    #This needs two passes of the array, but uses builtins, which are
written in c, and are therefore faster than the equivalent python
    return min(a), max(a)

def minmax2(a):
    #This only takes one pass, but is python, which is not as fast as C code.
    #This also has the advantage of allowing you to easily customize
your lookups and comparisons
    minVal = a[0]
    maxVal = a[0]
    for v in a:
        if v < minVal:
            minVal = v
        elif v > maxVal:
            maxVal = v
    return minVal, maxVal

Other techniques to consider:  If order is not important, take the
first and last values after sorting (or after sorting a copy).

You will want to profile each version, to find out what is best in
your specific case.

If you want to return the indexes of the maximum and minimum, you will
need to use the minmax2 function, modified slightly:

def minmaxIndexes(a):
    """returns a tuple of the indexes of the (first) minimum and
maximum in the array"""
    minVal = 0, a[0]
    maxVal = 0, a[0]
    for v in enumerate(a):
        if v[1] < minVal[1]:
            minVal = v
        elif v[1] > maxVal[1]:
            maxVal = v
    return minVal[0], maxVal[0]

Rich "Roadie Rich" Lovely

There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.

More information about the Tutor mailing list