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:
- Create a matrix
- Find out which is the largest element in the Matrix
- 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
~Interesting code
– ClMend