Find maximum and minimum value of a matrix
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
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)
>>>
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))