-2
Problem: Having a 5 5 matrix filled with random (real) values between 0 and 99, show which is the second highest value existing in the matrix.
Can’t use numpy or similar.
My solution:
n=2
def constroi_matriz(n):
import random
matriz =[[]]
linha =[]
for i in range(n):
for j in range(n):
num = random.randint(0,99)
linha.append(num)
matriz.append(linha)
linha =[]
matriz.pop(0)#excluir a posicao que contem []
return matriz
def segundo_maior(matriz):
maior = max(max(matriz))
for i in range(len(matriz)):
for j in range(len(matriz)):
if matriz[i][j] == maior:
matriz[i].remove(maior)
print(matriz)
return max(max(matriz))
matriz = constroi_matriz(2)
print(f"A matriz é {matriz}")
print(f"O segundo maior é: {segundo_maior(matriz)}")
I don’t know why I sometimes get error from "builtins.Indexerror: list index out of range"
Have you done the table test of your code? There are several strange things in it: 1) no need to start
matriz
with an empty list and will then remove it; 2)max(max(matriz))
will not return the highest matrix value; 3) you define the functionsegundo_maior
and never calls it; 4) in the functionsegundo_maior
you delete matrix elements, which doesn’t make much sense;– Woss
Woss: yes. and I couldn’t figure out what was wrong...
– Ed S
Can you show us the results of your table test?
– Woss
@Woss: I did trying to run on paper and did not find the error in my logic!
– Ed S
@Woss: I had forgotten to put the function calls. I edited the question!
– Ed S
I recommend starting studying as Find the largest and smallest element of a matrix; for the second largest, simply replicate the same lobe of the largest by adding the condition that the second largest cannot be greater than the largest. On how to create an array, see How to create a python array
– Woss