Example code - Misc

From 22113
Jump to navigation Jump to search

Files used in example

Our favorite data file: ex1.dat

Closest to zero

There are a lot of numbers in this file. Which number is the closest to zero and where is it (row/column) ?
This is more complicated because there are both positive and negative numbers in the file.
In order to demonstrate some of the new functions/methods, I pull the entire file into memory. This problem could be solved by reading line-by-line and not keeping all the data.

#!/usr/bin/env python3
# Read file, keep track of where numbers are
numbers = list()
with open("ex1.dat", "r") as number_file:
    line_count = 0
    for line in number_file:
        for field_pos, field_value in enumerate(line.split()):
            try:
                number = float(field_value)
                numbers.append((line_count, field_pos, number))
            except ValueError:
                pass
        line_count += 1
if len(numbers) > 0:
    minimum = min(numbers, key=lambda x: abs(x[2]))
    # Display Human numbers.
    print(minimum[2], 'in line', minimum[0]+1, 'column', minimum[1]+1, 'is closest to 0.')
else:
    print("No numbers in the file.")

Notice how I actually don't care if all the fields are numbers, nor if there is the same amount of fields on every row. By changing min to max I can find the number furthest away from 0. The runtime is linear to the amount of numbers/words in the file, as I am not doing any sorting.