Return the positions of the largest number in a matrix

Asked

Viewed 745 times

2

I need a code that returns the position of the largest element of the matrix, and if this element repeats, the code returns all positions that this largest element appears.

Below, in my code, I can return the highest value, but not your position:

  • maior: is the greatest value
  • posição: position on the line the highest value is
  • vez: is a counter of how many times I’ve circled the lines (for example: I’m on line 2)
from random import randint
maior = 0
posição = 0
matriz = []
vez = 0
for i in range (4):
    linha = []
    vez = vez + 1
    for j in range (4):
        linha.append(randint(1,10))
        if linha[j] > maior:
            maior = linha[j]
            posição  = j
            linha = vez

    matriz.append(linha)

print (matriz)
print ("maior: ", maior)
print ("posição do maior número: ", posição)
print ("linha: ", linha)

3 answers

2

Hi, your code is almost certain. The position depends on i,j. Then you have to keep the value of i,j:

from random import randint
matriz = [-1]*4
j = 0
maior = 0
posição = ()
for i in range (4):
    for j in range (4):        
        matriz[j] = randint(1,10)
        if matriz[j] > maior:
            maior = matriz[j]
            posição = (i,j)
        j = j + 1
    print (matriz)
    print ("posição do maior número: ", posição)
print ("maior número da matriz: ", maior)

To get all positions that the largest number occurs, Voce will have to create a list of pairs, and if the largest number changes Voce will have to restart the list of pairs and start adding values to it again.

1


If the largest element can repeat itself, then you need to have a list of all positions.

If the number is equal to the largest, you add the position in this list. But if any other higher number is still found, the list of previous positions should be dropped and a new one should be started:

from random import randint
maior = 0
matriz = []
tamanho = 4
posicoes = []
for i in range(tamanho):
    linha = []
    for j in range(tamanho):
        n = randint(1, 10)
        if n > maior: # achei um maior, começa uma nova lista de posições
            posicoes = [(i, j)]
            maior = n
        elif n == maior: # igual ao maior, adicione a posição na lista
            posicoes.append((i, j))
        linha.append(n)

    matriz.append(linha)

print (matriz)
print ("maior: ", maior)
print ("posições do maior número: ", posicoes)

I am storing the positions in tuples, containing the values of i and j (since you need both values to have the correct position).

I also deleted the variable vez, which I felt was unnecessary.

  • ~Interesting code

1

I noticed that you’re trying to agglutinate all the tasks into one thing.

It would be better to divide your problem into smaller and simpler steps where in each of these steps you do just the essentials to solve a minor problem.

Focusing on your question:

I need a code that returns the position of the largest element in the matrix, and if this element repeats, that the code returns all positions that this largest element appears.

I see the following steps:

  1. Create a matrix
  2. Find out which is the largest element in the Matrix
  3. Find out the positions of occurrence of the largest element in the Matrix.

To create a matrix has no mystery, it is a list composed of isomorphic lists where the amount of lines in the outer list is the same amount of elements contained in one of the inner lists. To simplify is a list where the number of rows is the same number of columns, translating it into comprehensilist on:

lambda d: [[randint(1,10) for _ in range(d)] for _ in range(d)]

A list of random numbers, between 1 and 10, where the number of rows is the same as the number of columns.

To find the largest element of the matrix create a list with the largest elements of each row and from that list only find the largest element and this will be the largest element of the matrix:

lambda m: max(list(map(max, m)))

The most laborious is to find the positions of occurrence of the largest element and even then it is nothing too much. It is to precorrer the rows of the matrix collect the indices of these occurrences and create a tuple (row, column) from where were found occurrence of the largest element:

def posição(elemento, matriz):
  ocorrencias = []
  for linha in range(len(matriz)):
    o = [i for i,v in enumerate(matriz[linha]) if v==elemento]
    for i in o:      
      ocorrencias.append((linha,i))
  return ocorrencias 

Putting it all together:

import pprint #Usado para melhorar a impressão da matriz 
from random import randint

matriz = lambda d: [[randint(1,10) for _ in range(d)] for _ in range(d)]

maior = lambda m: max(list(map(max, m)))

def posição(elemento, matriz):
  ocorrencias = []
  for linha in range(len(matriz)):
    o = [i for i,v in enumerate(matriz[linha]) if v==elemento]
    for i in o:      
      ocorrencias.append((linha,i))
  return ocorrencias    

mat = matriz(4)
mat_max = maior(mat)
mat_max_occor = posição(mat_max, mat)    

pprint.pprint(mat,width=20) #Usado para melhorar a impressão da matriz 
print(f'\nvalor máximo:{mat_max}')
print(f'Posições de ocorrencia do valor máximo:{mat_max_occor}')

Code working in Repl.it: https://repl.it/repls/UltimateCulturedPresses

Functions used:
max(): https://docs.python.org/3/library/functions.html#max
map(): https://docs.python.org/3/library/functions.html#map
list(): https://docs.python.org/3/library/functions.html#func-list
enumerate(): https://docs.python.org/3/library/functions.html#enumerate

Browser other questions tagged

You are not signed in. Login or sign up in order to post.