简体   繁体   中英

Find minimum, maximum, and average value of a text file

i've been desperately trying to find an answer to this for a class, and I cannot seem to find one. I need to find the minimum, maximum, and average value from given values received from a text file. Here's what I have right now. Nothing even prints and I'm not getting any errors. I'm going based off of an outline that my professor gave us, but still some of the stuff isn't making sense.

#2
inputFilename=input("Enter the filename: ")
inputFile=open(inputFilename, "r")
for item in inputFile:
    print(item.rstrip())
#3
item=inputFile.readline()
data=item.rstrip()
smallest, largest, sum=data, data, data
count=1
for item in inputFile:
    data=int(item.rstrip())
    if data<=item.strip():
        largest=data
    if data>=item.strip():
        smallest=data
    sum=
    count=count+1
print("smallest: ", smallest, "largest: ",largest, "average: ")
inputFile.close()

Assuming your input file is integers separated by newlines, here are two approaches.

Approach 1 : Read all elements into a list, operate on the list

# Open file, read lines, parse each as an integer and append to vals list
vals = []
with open('input.txt') as f:
    for line in f:
        vals.append(int(line.strip()))

print(vals)     # Just to ensure it worked

# Create an average function (much more verbose than necessary)
def avg(lst):
    n = sum(lst)
    d = len(lst)
    return float(n)/d

# Print output
print("Min: %s" % min(vals))    # Min: 1
print("Max: %s" % max(vals))    # Max: 10
print("Avg: %s" % avg(vals))    # Avg: 5.5

Approach 2: Read one element at a time, maintain min/max/sum/count for each element:

_min = None
_max = None
_sum = 0
_len = 0
with open('input.txt') as f:
    for line in f:
        val = int(line.strip())
        if _min is None or val < _min:
            _min = val
        if _max is None or val > _max:
            _max = val
        _sum += val
        _len += 1

_avg = float(_sum) / _len

# Print output
print("Min: %s" % _min)     # Min: 1
print("Max: %s" % _max)     # Max: 10
print("Avg: %s" % _avg)     # Avg: 5.5

(The input file was just the integers 1-10, separated by newlines)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM