简体   繁体   English

如何在文本文件中找到最小的数字(Python 2.5)

[英]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. 到目前为止,我的代码找到了文本文件中最大的数字,但它没有找到最小的数字,当它运行时,最小的数字仍为0,而最大的数字为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: numbers.txt看起来像:

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. 我要感谢@Martijn Pieters和@Gexos解释我做错了什么。 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 ; 请注意,您要使用if在这里,不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. 我分别使用float('-inf')float('inf')启动了largestIntsmallestInt ,数字保证比其他任何东西都小。 This makes the first time you test for largestInt < number always true, whatever number is on the first line. 这使得第一次测试largestInt < number 始终为 true,无论第一行是什么数字。

Comparing strings is done lexicographically, where characters are compared one by one; 比较字符串是按字典顺序进行的,其中字符逐一进行比较; 10 is smaller than 2 because 1 sorts before 2 . 10小于2因为12之前排序。

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: 您可以使用max()min()内置函数来轻松实现,但效率会低一些,因为内部这些函数也可以执行循环:

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. 虽然我通常喜欢使用minmax解决方案,但在这种情况下需要两次线性传递,并且需要大量内存开销。 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. 您需要将该line转换为字符串中的int: int(line.strip())当前您正在将int与字符串进行比较。 You should also cast the assignment in largestInt = int(line.strip()) and the same for smallestInt . 您还应该在largestInt = int(line.strip())赋值,对于smallestInt

You should not be using while . 你不应该使用while while is for looping, not for comparing. while对于循环,而不是比较。 You should be using if . 你应该使用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. 你需要在最有可能将它们转换为数字的某个阶段调用它们的int函数。

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. 使用with确保文件在列表理解后自动关闭,这是一种很好的做法。 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. 然后在该列表上调用minmax

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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