I need the highest and lowest note of the matrix, but when I print out a vector with the three notes what do I do? I’m using min and max

Asked

Viewed 47 times

-2

def mostrandomatriz():
   for l in range(0,5):
       #estética 
       print(f"Aluno {l+1}")
       print("|-----|")
       #leitura da coluna e impressão da matriz
       for c in range(0,3):
          print(f"|{matriz[l][c]:^5}|")
       #estética   
       print("|-----|")
   
print ("======================|")
for l in range(0,5):
   for c in range(0,3):
    matriz[l][c]= float(input(f"Aluno {l+1}| {c+1}ª Nota = " ))#Receber todas as notas
   print ("======================|")
print("\n")

mostrandomatriz()

Maior = max(matriz)
Menor = min(matriz)

print(f"Maior Nota = {Maior} Menor Nota = {Menor}")
  • the code is incomplete. How you defined this matrix?

  • matriz = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]

2 answers

1

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("|-----|")

-1


the min and max built-in python is not good for searching for minimums and maximums in multidimensional arrays. Use this package functions numpy and it’s gonna work.

import numpy as np

def mostrandomatriz():
   for l in range(0,5):
       #estética 
       print(f"Aluno {l+1}")
       print("|-----|")
       #leitura da coluna e impressão da matriz
       for c in range(0,3):
          print(f"|{matriz[l][c]:^5}|")
      #estética   
       print("|-----|")

matriz = np.zeros([5,3])

print ("======================|")
for l in range(0,5):
   for c in range(0,3):
    matriz[l][c]= float(input(f"Aluno {l+1}| {c+1}ª Nota = " ))#Receber todas as notas
   print ("======================|")
print("\n")

Maior = np.max(matriz)
Menor = np.min(matriz)

print(f"Maior Nota = {Maior} Menor Nota = {Menor}")

Browser other questions tagged

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