Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exercise: Calculates the minimum and maximum score for each student.

total beginner to programming here, need your guidance.

I'm learning python from some free online course, then come across this particular exercise, which I already solved, but puzzling me having two different way produce different result. So here it goes..

The question: Using the text file studentdata.txt (shown below) write a program that calculates the minimum and maximum score for each student. Print out their name as well.

studentdata.txt:
joe 10 15 20 30 40
bill 23 16 19 22
sue 8 22 17 14 32 17 24 21 2 9 11 17
grace 12 28 21 45 26 10
john 14 32 25 16 89

My final attempt:

xFile = open("studentdata.txt", "r")

for xLine in xFile:
    xList = xLine.split()
    min = 100
    max = 0

    for x in xList[1:]:
        if int(x) > max:
            max = int(x)
    for x in xList[1:]:
        if int(x) < min:
            min = int(x)

print(xList[0],"\tmin: ",min,"\tmax: ",max)

xFile.close()

Result:

joe min: 10 max: 40
bill min: 16 max: 23
sue min: 2 max: 32
grace min: 10 max: 45
john min: 14 max: 89

Then I compared it to the given answer provided by the site (I rewrite it in my style):

xFile = open("studentdata.txt", "r")

for xLine in xFile:
    xList = xLine.split()
    print(xList[0],"\tmin: ",min(xList[1:]),"\tmax: ",max(xList[1:]))

xFile.close()

Which is more simple, but it produce slightly different (but vital) result:

joe min: 10 max: 40
bill min: 16 max: 23
sue min: 11 max: 9
grace min: 10 max: 45
john min: 14 max: 89

Notice that the result for sue is different. The 'automatic' version doesn't produce the right result. How this happened?

Thanks.

like image 891
NunNo Avatar asked Aug 11 '26 03:08

NunNo


1 Answers

The problem with the second version is that it doesn't convert the scores to int before comparison. When comparing strings '32' comes before '9'.

You can fix the issue by converting the scores to int before using min and max:

with open("studentdata.txt", "r") as xFile:
    for xLine in xFile:
        xList = xLine.split()
        scores = [int(x) for x in xList[1:]]
        print(xList[0],"\tmin: ",min(scores),"\tmax: ",max(scores))
like image 171
niemmi Avatar answered Aug 12 '26 16:08

niemmi