Question

i need to print out average height from a .txt file. How do I write it in an easy way? The .txt file has these numbers:

12
14
59
48
45
12
47
65
152

this is what i've got so far:

import math

text = open(r'stuff.txt').read()
data = []
with open(r'stuff.txt') as f:
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)

biggest = min(data)
smallest = max(data)
print(biggest - smallest)
Was it helpful?

Solution

To compute the average of some numbers, you should sum them up and then divide by the number of numbers:

data = []
with open(r'stuff.txt') as f:
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)

print(sum(data)/len(data))

OTHER TIPS

# import math -- you don't need this

# text = open(r'stuff.txt').read() not needed.
# data = [] not needed

with open(r'stuff.txt') as f:
    data = [float(line.rstrip()) for line in f]

biggest = min(data)
smallest = max(data)
print(biggest - smallest)
print(sum(data)/len(data))
data = [float(ln.rstrip()) for ln in f.readlines()]  # Within 'with' statement.
mean_average = float(sum(data))/len(data) if len(data) > 0 else float('nan')

That is the way to calculate the mean average, if that is what you meant. Sadly, math does not have a function for this. FYI, the mean_average line is modified in order to avoid the ZeroDivisionError bug that would occur if the list had a length of 0- just in case.

Array average can be computed like this:

print(sum(data) / len(data))

A simple program for finding the average would be the following (if I understand well, your file has one value in each line, if so, it has to be similar to this, else it has to change accordingly):

import sys

f = open('stuff.txt', 'rU')    
lines = f.readlines()    
f.close()

size =  len(lines)
sum=0
for line in lines:
    sum = sum + float(line.rstrip())

avg = sum / float(size)    
print avg,

Not the best that can be in python but it's quite straight forward I think...

A full, almost-loopless solution combining elements of other answers here:

with open('stuff.txt','r') as f:
    data = [float(line.rstrip()) for line in f.readlines()]
    f.close()
mean = float(sum(data))/len(data) if len(data) > 0 else float('nan')

and you don't need to prepend, append, enclose or import anything else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top