Geesh_SO
Geesh_SO

Reputation: 2206

Simple Python headache with number comparison

To keep a clean question, the problem is commented inside the code :)

theOpenFile = open('text.txt', 'r')
highest = 0
for myCurrentString in theOpenFile.readlines():

                                          ## Simple string manipulation
    stringArray = myCurrentString.split() ## to get value, this seems to
    series = stringArray[0].split('.')[0] ## work perfectly when I
                                          ## "print series" at the end

    if series > highest:                  ## This doesn't work properly,
        highest = series                  ## although no syntantic or
        print "Highest = " + series       ## runtimes errors, just wrong output

    print series
theOpenFile.close()

Output

Highest = 8
8
Highest = 6
6
Highest = 6
6
Highest = 8
8
Highest = 8
8
Highest = 7
7
Highest = 4
4

Upvotes: 1

Views: 1001

Answers (2)

jfs
jfs

Reputation: 414235

Assuming there is a dot before a whitespace on each non-blank line in the file:

with open('text.txt') as file:
  highest = max(int(line.partition('.')[0]) for line in file if line.strip())

Upvotes: 1

Blender
Blender

Reputation: 298176

You're comparing strings, not numbers, so things can get a bit strange. Convert your variable to a float or an int and it should work

with open('text.txt', 'r') as theOpenFile:
    highest = 0
    for myCurrentString in theOpenFile:
        stringArray = myCurrentString.split()

        try:
            series = float(stringArray[0].split('.')[0])
        except ValueError:
            # The input wasn't a number, so we just skip it and go on
            # to the next one
            continue

        if series > highest:
            highest = series
            print "Highest = " + series

        print series

A cleaner way of doing it would be like this:

with open('text.txt', 'r') as handle:
    numbers = []

    for line in handle:
        field = line.split()[0]

        try:
            numbers.append(float(field))  # Or `int()`
        except ValueError:
            print field, "isn't a number"
            continue

    highest = max(numbers)

Upvotes: 2

Related Questions