Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 = []
withopen('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)defavg(lst):
    n = sum(lst)
    d = len(lst)
    returnfloat(n)/d

# Print outputprint("Min: %s" % min(vals))    # Min: 1print("Max: %s" % max(vals))    # Max: 10print("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 = 0withopen('input.txt') as f:
    for line in f:
        val = int(line.strip())
        if _minisNoneor val < _min:
            _min = val
        if _maxisNoneor val > _max:
            _max = val
        _sum += val
        _len += 1

_avg = float(_sum) / _len# Print outputprint("Min: %s" % _min)     # Min: 1print("Max: %s" % _max)     # Max: 10print("Avg: %s" % _avg)     # Avg: 5.5

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

Post a Comment for "Find Minimum, Maximum, And Average Value Of A Text File"