I\'m trying to calculate max/min from a text file containing numbers, but can\'t figure out how. I was able to do count and total, but not max/min. Any help would be much apprec
Simpler way to achieve what you are doing is:
num_list = [float(num) for num in inputFile.read().split())
# OR, num_list = map(float, inputFile.read().split())
counter = len(num_list)
total = sum(num_list)
# Your desired values
max_val = max(num_list)
min_val = min(num_list)
In case you want to do it in your code, you may do:
min_value, max_value = 999, -999 # Range based on the value you are sure you data will lie within
for numbers in inputFile:
numbers = float(numbers.rstrip())
# ... your other logic
if min_val > numbers:
min_val = numbers
if max_value < numbers:
numbers = numbers
If you're working with numbers, I'd suggest using the numpy
module. With it, you can achieve what you want very quickly - depending on your input file:
import numpy as np
x = np.loadtxt("Numbers.txt")
print('Total:', np.sum(x))
print('Average:', np.average(x))
print('Max:', np.amax(x))
print('Min:', np.amin(x))
and much more... if your input file isn't as simple to read, you can try using np.genfromtxt to extract the data.