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!
Pair Comparison (Efficient method): Select two elements from the matrix one from the start of a row of the matrix another from the end of the same row of the matrix, compare them and next compare smaller of them to the minimum of the matrix and larger of them to the maximum of the matrix.
M = max( A ) returns the maximum elements of an array. If A is a vector, then max(A) returns the maximum of A . If A is a matrix, then max(A) is a row vector containing the maximum value of each column of A .
M = min( A ) returns the minimum elements of an array. If A is a vector, then min(A) returns the minimum of A . If A is a matrix, then min(A) is a row vector containing the minimum value of each column of A .
The min is simply the lowest observation, while the max is the highest observation. Obviously, it is easiest to determine the min and max if the data are ordered from lowest to highest. So for our data, the min is 13 and the max is 110.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With