Here is the question:
Suppose that you have a text file that contains a list of floating-point numbers, one number per line. Write Python program that will search through the file and find and print to the console the smallest number.
We can't use functions like .readlines()
, with
, try
, inf
, or None
.
This is what I have and I am stuck.
in_file = open("floating-point.txt", "r")
def get_smallest_float():
count = 0
for line in in_file:
num = float(line)
if count == 0:
if num > 0:
smallest = num
count = count + 1
elif count == 1:
if num < smallest:
num = smallest
count = count + 1
in_file.close()
return smallest
get_smallest = get_smallest_float(in_file)
print(get_smallest)
There were a few logic and syntax errors, but this seemed to work. I removed the positive number test. The problem stated smallest number, not smallest absolute value. The assignment of the new minimum was also reversed. This solution does not handle cases of a tie.
and the diff:
Given this floating-point.txt:
the result is -0.01
Given the floating-point.txt with these:
the result is -0.02