Last modified on 8 February 2012, at 12:04

Algorithms/Find maximum/Python method 1

Python (2.5) source code. The code needs to be reviewed.

def findmax(a):
 
    if len(a) == 0:
        return 0
 
    curr_max = a[0]
 
    for i in a:
        if i > curr_max:
            curr_max = i
 
    return curr_max

Simple example of how to use the function:

print findmax( [12, 13, 555, 124, 342] )

Output should be: 555


Another way to implement the algorithm:

def imax( iterable, key=lambda x: x ):
    """returns largest item, as input could take iterator or sequence
    "key" function will be applied on every item, before comparison is made
    >>> imax( [12,3,4, 89, 90,88] )
    90
    """
    current_max = None
    for x in iterable:
        if current_max is None or key(x) > key( current_max ):
            current_max = x
    return current_max

Simple example of how to use the function:

print imax( [12, 13, 555, 124, 342] )
print imax( [12, 13, 555, 124, 342], lambda x: 1.0/x )