How find the smallest floating point number in a .txt file?

110 Views Asked by At

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)
3

There are 3 best solutions below

0
On

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.

in_file = open("floating-point.txt", "r")


def get_smallest_float():
    count = 0
    for line in in_file:
        num = float(line)
        if count == 0:
                smallest = num
                count = count + 1
        elif count > 0:
            if num < smallest:
                smallest = num
                count = count + 1
    in_file.close()
    return smallest

get_smallest = get_smallest_float()
print(get_smallest)

and the diff:

diff -u before after
--- before  2023-11-03 22:23:58
+++ after   2023-11-03 22:23:19
@@ -6,15 +6,15 @@
     for line in in_file:
         num = float(line)
         if count == 0:
-            if num > 0:
                 smallest = num
                 count = count + 1
-        elif count == 1:
+        elif count > 0:
             if num < smallest:
-                num = smallest
+                smallest = num
                 count = count + 1
     in_file.close()
     return smallest
 
-get_smallest = get_smallest_float(in_file)
+get_smallest = get_smallest_float()
 print(get_smallest)

Given this floating-point.txt:

1.0
1.1
1.2
0.9
-.01
.01

the result is -0.01

Given the floating-point.txt with these:

1.0
1.1
1.2
0.9
-.01
.01
-.02
-.001

the result is -0.02

0
On

The constraints are bizarre. However, given those constraints then it's as simple as:

for i, fv in enumerate(map(float, open("floating-point.txt"))):
    lo = min(lo, fv) if i else fv #type: ignore

print(lo) #type: ignore
0
On

I'd expect something more like:

for line in in_file:
    num = float(line)
    if (count == 0) or (num < smallest)
        smallest = num
        count = count + 1