Skip to content Skip to sidebar Skip to footer

Why Can't I Find Max Number In A File Like This?

I'm quite new to python, though I have a lot of experience with bash. I have a file that consists of a single column of numbers, and I would like to find the largest number in the

Solution 1:

num is a string, not a number. Turn it into an integer first using int():

num = int(num)

You are comparing text, so it is ordered lexicographically, '9' > '80' because the ASCII character '9' has a higher codepoint than '8':

>>> '9' > '80'True

After the '9' line, all other lines either have an initial digit that is smaller than '9', or the line is equal.

You could use the max() function instead, provided you first use map() to turn all lines into integers:

withopen('jan14.nSets.txt','r') as data:
    i = max(map(int, data))

or use a generator expression (in Python 2, more memory efficient than map()):

withopen('jan14.nSets.txt','r') as data:
    i = max(int(num) for num in data)

Both pull in all lines from data, map the lines to integers, and determine the maximum value from those.

Post a Comment for "Why Can't I Find Max Number In A File Like This?"