Doubt in my code is not printing correctly

Asked

Viewed 98 times

2

question: Using the text file notes_students.dat write a program that calculates the minimum and maximum score of each student and prints the name of each student along with their maximum and minimum score. filing cabinet:

jose 10 15 20 30 40
pedro 23 16 19 22
suzana 8 22 17 14 32 17 24 21 2 9 11 17
gisela 12 28 21 45 26 10
joao 14 32 25 16 89

my code:

arq=open('notas_estudantes.dat','r')
conteudo=arq.readlines()
arq.close()
for item in conteudo:
    lista=item.split()
    lista.sort()
    print(lista[-1],':','Nota Maxima:',lista[-2],'Nota Minima:',lista[0])

when will I print this:

jose : Nota Maxima: 40 Nota Minima: 10
pedro : Nota Maxima: 23 Nota Minima: 16
suzana : Nota Maxima: 9 Nota Minima: 11
gisela : Nota Maxima: 45 Nota Minima: 10
joao : Nota Maxima: 89 Nota Minima: 14

the others are all correct however when it comes to the part of Uzana it does not give the correct result, I wonder if it is something error of Pyhton or it was myself that I missed something in the code.

  • My question is why the Sort ? For the stated purpose is not necessary the sort and of course it would be less efficient to sort the list.

3 answers

4

Your code that is wrong, when you perform the method call sort() It orders the list increasing but the data in the list returned by the method split() are of the type string, that is, when the method sort() is invoked it checks caractere por caractere of the data, see:

>>> conteudo = "suzana 8 22 17 14 32 17 24 21 2 9 11 17"
>>> dados = conteudo.split(" ")
['suzana', '8', '22', '17', '14', '32', '17', '24', '21', '2', '9', '11',
>>> dados.sort()
['11', '14', '17', '17', '17', '2', '21', '22', '24', '32', '8', '9', 'suzana']

Got it ? '11' comes before "2" because he checks caractere por caractere. What you could do to solve it is:

arquivo = open("notas_estudantes.dat", "r")
conteudo = arquivo.readlines()
arquivo.close()
for item in conteudo:
    lista = item.split()
    nome = lista.pop(0)
    lista.sort(key = int)
    print(nome, ":", "Nota Máxima:", lista[-2], "Nota Minima:", lista[0])
  • thank you very much!

  • Come on, we’re here for that. Any questions don’t hesitate to post here on Stack.

4

You’re treating the notes like strings, then when you sort Python puts "1", "10", in front of "2", "4" etc. In this case the best solution is to work with them as a numerical format.

# ...
for item in conteudo:
    lista = item.split()  # converte a linha lida em uma array
    nome = lista.pop(0)  # retira o nome de dentro do array
    notas = [int(i) for i in lista]  # cria um novo array com o que sobrou de
                                     # 'lista', convertendo cada elemento em um
                                     # número inteiro.

    # por fim, usa min() e max() para obter os valores agora que eles são números.
    print(nome, ':', 'Nota Maxima:', max(notas), 'Nota Minima:', min(notas))

Of course this is ONE solution, but as you want to know the maximum and minimum grades (want to treat them as values) I preferred the more "numerical approach".

3


As said before, you have to be careful about the types you are dealing with in your containers. I made another implementation to generate the expected result for you. I removed the names, and converted the rest to integers, making it easier to remove max and min from the list.

arq = open('arquivo.dat','r')
conteudo = arq.readlines()
arq.close()
for item in conteudo:
    lista = item.split()
    aluno = lista[0]
    del lista[0]
    notas = list(map(int, lista))
    print('Aluno: {}, Nota max: {}, Nota Min: {}'.format(aluno, max(notas), min(notas)))

Browser other questions tagged

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