简体   繁体   中英

How to find the smallest number in a text file (Python 2.5)

So far, my code finds the largest number in a text file but it doesn't find the smallest number, when it's run the smallest number is still 0 while the largest is 9997.

    integers = open('numbers.txt', 'r') # opens numbers.txt

largestInt = 0 # making variables to store the largest/smallest int
smallestInt = 0

# loop where we check every line for largest/smallest int
for line in integers:
    while largestInt <= line.strip():
        largestInt = line
    while smallestInt >= line.strip():
        smallestInt = line

# print results
print "Smallest = ", smallestInt
print "Largest = ", largestInt

numbers.txt looks like:

6037
-2228
8712
-5951
9485
8354
1467
8089
559
9439
-4274
9278
-813
1156
-7528
1843
-9329
574

and so on.

What's wrong here? If I'm doing something wrong, or the logic is incorrect please correct me.

EDIT

I'd like to say thanks to @Martijn Pieters and @Gexos for for explaining what I'm doing wrong. I understand why my code works now!

Final Code:

integers = open('numbers.txt', 'r') # opens numbers.txt

largestInt = 0 # making variables to store the largest/smallest int
smallestInt = 0

# loop where we check every line for largest/smallest int
for line in integers:
    if largestInt <= int(line.strip()): # converted a string into an int
        largestInt = int(line.strip()) # made that int into largestInt
    if smallestInt >= int(line.strip()): # converted a string into an int
        smallestInt = int(line.strip()) # made that int into smallestInt

integers.close() # closes the file

# print results
print "Smallest = ", smallestInt
print "Largest = ", largestInt

Results

Smallest =  -9993
Largest =  9997

You are comparing strings, not integers; turn your line into an integer before comparing:

largestInt = float('-inf')
smallestInt = float('inf')

for line in integers:
    number = int(line)
    if largestInt < number:
        largestInt = number
    if smallestInt > number:
        smallestInt = number

Note that you want to use if here, not while ; the latter creates a loop.

I started largestInt and smallestInt with float('-inf') and float('inf') , respectively, numbers guaranteed to be smaller and larger than anything else. This makes the first time you test for largestInt < number always true, whatever number is on the first line.

Comparing strings is done lexicographically, where characters are compared one by one; 10 is smaller than 2 because 1 sorts before 2 .

You could use the max() and min() built-in functions for ease, but it'll be a bit less efficient because internally these functions do loops as well:

numbers = {int(line) for line in integers}
largestInt = max(numbers)
smallestInt = min(numbers)

While I usually like solutions that use min and max , that would require two linear passes in this case, with a lot of memory overhead. Here's a method that needs one linear pass and constant memory:

with open('numbers.txt') as infile:
    smallest, largest = '', None
    for line in infile:
        n = int(line)
        smallest = min(n, smallest)
        largest = max(n, largest)
    print "the smallest number is", smallest
    print "the largest number is", largest

As others have stated, you need to convert your lines to integers first. Additionally, your script will not output the correct minimum number if that number is bigger than zero. To fix this, set both your maximum number and minimum number to the first entry in your file. Then check all other numbers, and see if they're bigger/smaller than the current number.

with open('numbers.txt', 'r') as data_file:
    num = int(next(data_file))
    min_num, max_num = num, num
    for line in data_file:
        num = int(line)
        if num > max_num:
            max_num = num
        elif num < min_num:
            min_num = num

print 'Smallest number: {}'.format(min_num)
print 'Largest number: {}'.format(max_num)

This can also be solved with list comprehensions:

nums = [int(line) for line in open('numbers.txt', 'r')]
min_num, max_num = min(nums), max(nums)
with open('number.txt') as f:
    s = [int(n.strip()) for n in f]
    print min(s), max(s)

A few things. You need to cast the line into an int from a string: int(line.strip()) currently you are comparing an int to a string. You should also cast the assignment in largestInt = int(line.strip()) and the same for smallestInt .

You should not be using while . while is for looping, not for comparing. You should be using if .

And last but not least make sure to close the file at the end. integers.close()

integers = open('numbers.txt', 'r')
intList = [int(x) for x in integers.readlines()]
print max(intList), min(intList)

You are comparing strings, not ints. You need to call the int function on them at some stage most likely to convert them to numbers.

This is an example of a different approach:

with open('numbers.txt', 'r') as f:
    integers = [int(n) for n in f.readlines()]

smallest = min(integers)
biggest = max(integers)

using with ensures the file is auto closed after the list comprehension, which is good practice. The list comprehension results in:

[6037, -2228, 8712, -5951, 9485, 8354, 1467, 8089, 559, 9439, -4274, 9278, -813, 1156, -7528, 1843, -9329, 574]

Then min and max are called on that list.

将tinyInt设置为0时需要注意的一件事。如果文本文档包含的最小数字为1,那么您仍然会以0作为答案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM