Reputation: 1
I am learning how to work with nested loops. I need to find the position of the maximum value of the 'n x n' matrix, and I understand that I need to include a conditional statement that stops the nested for loops once the maximum value is confirmed. So far I managed to program a nested loop that iterates through each row and column of the matrix to output its final position.
To find the maximum of the matrix, I know a possible approach is using:
max(sum(matrix, []))
However, I am not entirely sure where to place this condition to return what I am looking for.
Upvotes: 0
Views: 1814
Reputation: 284
import numpy as np
print("enter the dimensions")
m = int(input())
n = int(input())
print("enter the elements of the matrix")
list1 = []
for i in range(m):
list2 = []
for j in range(n):
list2.append(int(input()))
list1.append(list2)
print(np.asarray(list1))
max_elements = []
for i in range(m):
list1[i].sort()
max_element = list1[i][n-1]
max_elements.append(max_element)
max_elements.sort()
the_max_element = max_elements[m-1]
print(the_max_element)
I have used the concept of sorting the inner lists and then accessing the largest elements from them. Another sort is done on this new generated list to get the largest element. Hope the above code helps you. Have used numpy to print the list in a multi-dimensional format.
Upvotes: 0
Reputation: 11
You can try this steps:
Upvotes: 0
Reputation: 619
When you do for i in range(n)
, i
will increase in each iteration of the loop on its own. You don't need to increment it.
Here is how you would go about traversing the matrix:
n = len(matrix)
for i in range(n):
for j in range(n):
print('position ({}, {}) in matrix: {}'.format(i, j, n[i][j]))
So to find the position of the maximum value, you can keep track of the largest value you've seen so far, and the position of that value, like this:
n = len(matrix)
max_value = float('-inf')
max_position = None
for i in range(n):
for j in range(n):
value = n[i][j]
if value > max_value:
max_value = value
max_position = (i, j)
print('max value is {} at position ({}, {})'.format(
max_value,
max_position[0],
max_position[1]
))
Upvotes: 1