Reputation: 160
I want to return the max value of a matrix. For example this is my matrix:
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
I want to return the max so here '10'
This is my code but I have an error:
max = 0
for i in range(len(matrix)+1):
for j in range(len(matrix[0])+1):
if matrix[i][j] > matrix[i+1][j+1]:
max = matrix[i][j]
print(max)
Thanks in advance
Upvotes: 2
Views: 240
Reputation: 25489
Multiple ways to do it:
i = 0
to len(matrix) - 1
. Doing for i in range(len(matrix)):
does this for you. You don't need to do range(len(matrix) + 1))
. Also, you should only replace the current maxval if the element you're looking at is greater than maxval
.So,
maxval = -9999999
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] > maxval:
maxval = matrix[i][j]
print(maxval)
# Out: 10
Or, a more pythonic way is to iterate over the elements instead of accessing them through their indices
maxval = -9999999
for row in matrix:
for element in row:
if element > maxval:
maxval = element
# maxval: 10
Notice I use maxval
instead of max
so as not to shadow python's inbuilt max()
function.
numpy
array is a much better way to store matrices instead of lists of lists. Why? See this questionimport numpy as np
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
maxval = np.max(matrix)
# maxval: 10
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
rowmax = [max(row) for row in matrix]
maxval = max(rowmax)
# or in one line:
maxval = max(max(row) for row in matrix)
map
. This is essentially the same as the previous method.matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
maxval = max(map(max, matrix))
Upvotes: 1
Reputation: 633
you can try this.
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
max1 = 0
for sub_list in matrix:
for item in sub_list:
if item>max1:
max1=item
Upvotes: 1
Reputation: 61910
There are several issues with your code, I suggest you use the max function:
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
result = max(max(row) for row in matrix)
print(result)
Output
10
Upvotes: 6