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!
eugen :
One-liner:\n\nfor max:\n\nmatrix = [[1, 2, 4], [8, 9, 0]]\nprint (max(map(max, matrix))\n9\n\n\nfor min:\n\nprint (min(map(min, matrix))\n0\n",
2020-02-10T05:00:26
AdelaN :
If you don't want to use new data structures and are looking for the smallest amount of code possible:\n\nmax_value = max([max(l) for l in matrix])\nmin_value = min([min(l) for l in matrix])\n\n\nIf you don't want to go through the matrix twice:\n\nmax_value = max(matrix[0])\nmin_value = min(matrix[0])\n\nfor row in matrix[1:]:\n max_value = max(max_value, max(row))\n min_value = min(min_value, min(row))\n",
2019-12-10T10:01:38
A.J. Uppal :
Use the built-in functions max() and min() after stripping the list of lists:\n\nmatrix = [[1, 2, 4], [8, 9, 0]]\ndup = []\nfor k in matrix:\n for i in k:\n dup.append(i)\n\nprint (max(dup), min(dup))\n\n\nThis runs as:\n\n>>> matrix = [[1, 2, 4], [8, 9, 0]]\n>>> dup = []\n>>> for k in matrix:\n... for i in k:\n... dup.append(i)\n... \n>>> print (max(dup), min(dup))\n(9, 0)\n>>> \n",
2014-04-30T23:52:32
Serjik :
If you are going with the solution of flattening matrix in an array, instead of inner loop you can just use extend:\n\nbig_array = []\n\nfor arr in matrix:\n big_array.extend(arr)\n\nprint(min(big_array), max(big_array))\n",
2019-10-13T17:45:55
Newyork167 :
Try\n\nlargest = 0\nsmallest = 0\ncount = 0\nfor i in matrix:\n for j in i:\n if count == 0:\n largest = j\n smallest = j\n count = 1\n if j > largest:\n largest = j\n if j < smallest:\n smallest = j\n\n\nUPDATE\n\nFor splitting\n\nlargest = 0\ncount = 0\nfor i in matrix:\n for j in i:\n if count == 0:\n largest = j\n if j > largest:\n largest = j\n\n\nand do the same thing for smallest",
2014-04-30T23:37:24
mr.matt :
here is what i came up with\n\nM = [[1,2,4],[8,9,0]]\n\ndef getMinMax( M ):\n maxVal = 0\n for row in M:\n if max(row) > maxVal: maxVal = max(row)\n minVal = maxVal*1\n for row in M:\n if min(row) < minVal: minVal = min(row)\n\n return ( minVal, maxVal )\n\ngetMinMax( M )\n// Result: (0, 9) //\n",
2014-05-01T00:04:25