If I have a text file that contains strings and integers such as:

Alabama 3200
Denver 4500
Chicago 3200
Atlanta 2000

what code could I use to print the smallest number (2000) after reading in that textfile. I know I first have to split the text so I'm just operating on the integers...but I'm lost

Any suggestions?
Thanks

Recommended Answers

All 2 Replies

Use the min function to find the smallest number. Is it just me, or is there one person with 100 different ID's who posts every homework problem here, saying they don't have a clue==don't even try. If you are lost then there is very little we can do to help you. "I'm lost" doesn't mean anything without some code to show what that means.

test_file = [ "Alabama 3200",
              "Denver 4500", 
              "Chicago 3200",
              "Atlanta 2000" ]

print min([int(rec.split()[1]) for rec in test_file])

If you can not use min, but have to find it yourself, Google for "python find smallest number" and look at the second entry found, "Roles of Variables (v2, Python)".

smallest = min(numbers)

Say:

text = '''\
Alabama 3200
Denver 4500
Chicago 3200
Atlanta 2000
'''

def parseLine(line):
    s, t = line.split()
    return int(t), s

items = [ parseLine(line) for line in text.splitlines() ]

>>> print min(items)
(2000, 'Atlanta')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.