到目前为止,我的代码在文本文件中找到了最大的数字,但没有找到最小的数字,当它运行时,最小的数字仍然是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
看起来像:
6037
-2228
8712
-5951
9485
8354
1467
8089
559
9439
-4274
9278
-813
1156
-7528
1843
-9329
574
等等。
这里怎么了?如果我做错了什么,或者逻辑不正确,请纠正我。
EDIT
我要感谢@Martijn Pieters和@Gexos解释我做错了什么。我明白为什么我的代码现在工作了!
最终代码:
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
结果
Smallest = -9993
Largest = 9997
虽然我通常喜欢使用
min
和max
的解决方案,但在这种情况下,需要两次线性传递,并且会有大量内存开销。这是一种需要一次线性传递和恒定内存的方法:您正在比较字符串,而不是整数;在比较之前,请将行转换为整数:
注意,您要在这里使用
if
,而不是while
;后者创建一个循环。我从
largestInt
和smallestInt
开始,分别是float('-inf')
和float('inf')
,这两个数字保证比任何其他数字都要小和大。这使得第一次测试largestInt < number
总是为真,无论第一行的数字是多少。字符串比较是按字典顺序进行的,其中字符逐个比较;
10
小于2
,因为1
在2
之前排序。您可以轻松地使用
max()
和min()
内置函数,但效率会低一些,因为这些函数在内部也执行循环:正如其他人所说,您需要先将行转换为整数。此外,如果最小值大于零,脚本将不会输出正确的最小值。要解决此问题,请将最大值和最小值都设置为文件中的第一个条目。然后检查所有其他数字,看看它们是否比当前数字大/小。
这也可以通过列表理解来解决:
相关问题 更多 >
编程相关推荐