Question

I have this code wrote in python 3:

matrix = []
    loop = True
    while loop:
        line = input()
        if not line: 
            loop = False
        values = line.split()
        row = [int(value) for value in values]
        matrix.append(row)

    print('\n'.join([' '.join(map(str, row)) for row in matrix]))
    print('matrix saved')

an example of returned matrix would be [[1,2,4],[8,9,0]].Im wondering of how I could find the maximum and minimum value of a matrix? I tried the max(matrix) and min(matrix) built-in function of python but it doesnt work.

Thanks for your help!

Was it helpful?

Solution 3

Use the built-in functions max() and min() after stripping the list of lists:

matrix = [[1, 2, 4], [8, 9, 0]]
dup = []
for k in matrix:
    for i in k:
        dup.append(i)

print (max(dup), min(dup))

This runs as:

>>> matrix = [[1, 2, 4], [8, 9, 0]]
>>> dup = []
>>> for k in matrix:
...     for i in k:
...         dup.append(i)
... 
>>> print (max(dup), min(dup))
(9, 0)
>>> 

OTHER TIPS

One-liner:

for max:

matrix = [[1, 2, 4], [8, 9, 0]]
print (max(map(max, matrix))
9

for min:

print (min(map(min, matrix))
0

If you don't want to use new data structures and are looking for the smallest amount of code possible:

max_value = max([max(l) for l in matrix])
min_value = min([min(l) for l in matrix])

If you don't want to go through the matrix twice:

max_value = max(matrix[0])
min_value = min(matrix[0])

for row in matrix[1:]:
    max_value = max(max_value, max(row))
    min_value = min(min_value, min(row))

If you are going with the solution of flattening matrix in an array, instead of inner loop you can just use extend:

big_array = []

for arr in matrix:
   big_array.extend(arr)

print(min(big_array), max(big_array))

Try

largest = 0
smallest = 0
count = 0
for i in matrix:
    for j in i:
        if count == 0:
            largest = j
            smallest = j
            count = 1
        if j > largest:
            largest = j
        if j < smallest:
            smallest = j

UPDATE

For splitting

largest = 0
count = 0
for i in matrix:
    for j in i:
        if count == 0:
            largest = j
        if j > largest:
            largest = j

and do the same thing for smallest

here is what i came up with

M = [[1,2,4],[8,9,0]]

def getMinMax( M ):
    maxVal = 0
    for row in M:
        if max(row) > maxVal: maxVal = max(row)
    minVal = maxVal*1
    for row in M:
        if min(row) < minVal: minVal = min(row)

    return ( minVal,  maxVal )

getMinMax( M )
// Result: (0, 9) //

You could first decide to flatten this matrix and then find the corresponding maximum and minimum values as indicated below Convert the matrix to a numpy array

import numpy as np
matrix = np.array([[1, 2, 4], [8, 9, 0]])
mat_flattened = matrix.flatten()
min_val = min(mat_flattened)
max_val = max(mat_flattened)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top