AAZA
AAZA

Reputation: 1

Nested For Loops for Finding Largest Value

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

Answers (3)

Stan11
Stan11

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

Mihir Patel
Mihir Patel

Reputation: 11

You can try this steps:

  1. Assume that the fisrt element of the matrix is the one having maximum value i.e element at [0,0] position do following, store position in two variables (e.x. row=0,col=0) and the value in max
  2. Now, iterate through the matrix as you normally would and at every iteration check if the current element (position [i,j]) is greater than the one stored in max, if yes then replace the value of max with current element vList itemalue along with row and col and if no, then continue with next iteration.
  3. Return row and col.

Upvotes: 0

nog642
nog642

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

Related Questions