[Tutor] maximum value in a Numeric array

Alan Gauld alan.gauld at freenet.co.uk
Sat Dec 11 01:11:04 CET 2004

> I am trying to get the maximum value in a 2-D array.  I can use max
but it
> returns the 1-D array that the max value is in and I then I need to
do max
> again on that array to get the single max value.
> There has to be a more straightforward way...I have just not found
> I could also flatten the array to 1 D first then do max but the
array I am
> going to be working with is fairly large.

Two max() calls seems pretty straightforward to me!
It probably is possible to be slightly more efficient, but you will
to look at every value in the array at least once whatever you do.

The simple brute force approach is probably the best here:

# NOTE: untested code...
def maximum(matrix):
   max = None     # not 0 to cope with negative matrices
   for col in matrix:
      for elem in col:
         if not max or (elem > max): max = elem
   return max

This only touches each element once and you can't break out till
the end because you don't know that the last elemement won't be

However it might be possible to make it faster by sorting the
colums and just comparing the first elements. This is because
the sort will be in C rather than Python... But premature
optimisation would be pointless if the above works...

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list