Eric1108
Eric1108

Reputation: 47

Does max() not recognise 2 digit numbers?

I have a code which reads all files in a directory and appends the highest value from each file into a list. The problem is that it does recognise the number 10, but recognises all numbers 0-9. Each file contains the last three scores of each person, from 1-10. However, if the person scores 10, the program does not read that as the highest value, and chooses the second highest from the file and appends that to the list instead. The code works fine if none of their scores are 10. The code should then sort the list according to each person's highest score, which does work, but because it appended the wrong score to the list, therefore it sorts it incorrectly as well.

For example:

[3, 6, 8], highest score is 8, no problem

[6, 10, 9], highest score is 9, why?

The relevant section of code is below. P.s. I have imported all modules and declared all variables at the start (just not visible here), so that is not the problem. Thanks for all help

scores = []
for file in os.listdir(path):
    file = os.path.join(path, file)
    if os.path.isfile(file):
        with open(file, 'r') as txt_file:
            scores.append(max(str(n.strip()) for n in txt_file))

results = list(zip(files, scores))
results.sort(key=operator.itemgetter(1), reverse=True)
student_list = [x + ": " + y for x, y in results]

Upvotes: 0

Views: 497

Answers (1)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

the problem is specifically with this line:

scores.append(max(str(n.strip()) for n in txt_file))

you are grabbing the max str value, and strings compare the same way all other sequences do: compare first element, if they are the same compare next... so when you do:

max("10","9")

it first compares "1" against "9" and sees that "9" is considered greater so that is the string returned, you need to be converting them to ints for them to compare as ints:

scores.append(max(int(n.strip()) for n in txt_file))
                #  ^ right here

Although since you are opening every single file in a directory if any of the files contain anything other then valid numbers on every line this would fail, so you probably want a try/except, although I cannot give you an example without knowing how files is defined because scores and files need to be the same length.

Upvotes: 1

Related Questions