In your case, you can check the biggest and smallest in it loop who reads the notes:
maior = float('-inf')
menor = float('inf')
for l in range(0,5):
for c in range(0,3):
nota = float(input(f"Aluno {l+1}| {c+1}ª Nota = " ))
if nota > maior:
maior = nota
if nota < menor:
menor = nota
matriz[l][c]= nota
print(f"Maior Nota = {maior} Menor Nota = {menor}")
Of course if you want, you can also check only after reading:
# ler a matriz...
# verifica o maior e menor
maior = float('-inf')
menor = float('inf')
for linha in matriz:
for nota in linha:
if nota > maior:
maior = nota
if nota < menor:
menor = nota
print(f"Maior Nota = {maior} Menor Nota = {menor}")
Of course you can also use min
and max
, but they don’t work with lists, so either you go through them and call max
separately for each line, or else "flatten" the matrix:
# Opção 1: com itertools, "achata" a matriz
from itertools import chain
maior = max(chain(*matriz))
menor = min(chain(*matriz))
##############
# Opção 2: verificar o maior/menor em cada linha, e depois obtém o maior/menor dentre esses
# obtém o maior dentre os maiores de cada linha
maior = max(max(linha) for linha in matriz)
# obtém o menor dentre os menores de cada linha
menor = min(min(linha) for linha in matriz)
The problem with these solutions is that they need to go through the matrix twice: one to find the largest and one to find the smallest (which is the same problem with another answer). But I find it unnecessary, and I prefer the first solution I suggested: get the biggest and smallest in it loop that reads the data, so you don’t have to wander through the matrix over and over again.
Finally, it is worth remembering that lists in Python are dynamic and you do not need to create one with the correct dimensions, because it can grow as needed. That is, to read the data and add the notes in the matrix, you could do:
matriz = [] # começa como uma lista vazia
print ("======================|")
maior = float('-inf')
menor = float('inf')
for l in range(1, 6):
linha = [] # linha começa vazia
for c in range(1, 4):
nota = float(input(f"Aluno {l}| {c}ª Nota = " ))
if nota > maior:
maior = nota
if nota < menor:
menor = nota
linha.append(nota) # adiciona a nota na linha
matriz.append(linha) # adiciona a linha na matriz
print ("======================|")
Although a dictionary could also be used, whose key would be the student’s name/identifier, and its value would be the list of grades...
And to show the matrix, you can scroll through it without needing to range
's fixed:
def mostrandomatriz():
# para cada linha da matriz, começando "l" com 1 (assim não precisa somar 1 no print)
for l, linha in enumerate(matriz, start=1):
print(f"Aluno {l}")
print("|-----|")
for nota in linha: # para cada nota desta linha
print(f"|{nota:^5}|")
print("|-----|")
the code is incomplete. How you defined this matrix?
– Adam Basílio
matriz = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
– Monkey Martins