-2

I am trying to take the average of numbers from a text file and print it. I have gotten as far as getting the numbers to print. I am lost as to how I can assign the values to variables and get the average. The numbers must be formatted like this in the text file:

10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200

def main():

    numbersFile = open ('numbers.dat', 'r')

    for number in numbersFile:

        print number

main()

The expected result is:

"The average is 105"

Any help would be greatly appreciated. I tried to follow posting guidelines but I am new so correct any mistakes I made. Thank you for any help in advance!

Stormbot
  • 11
  • 1
  • 1
    it would be better if you posted the input file fragment – RomanPerekhrest Dec 09 '17 at 10:27
  • 2
    The average of a set of numbers is formed by summing up all numbers and dividing by their count. So in your loop you have to: 1) sum up the numbers, 2) count the numbers. Result is `sum / count`. – yacc Dec 09 '17 at 10:34

2 Answers2

0

You need to parse the numbers, int(number) will do that (if your input file contains one number per line) - then you add the number to a list (define it before the for as allNumbers = [] so you do not reinitialize it all the time to empty list inside the for. append your parsed number to it with allNumbers.append(mynumber).

Outside the for loop you return the numbers in the list:

The avg Function will compute the average (also see: Finding the average of a list )

def avg(myl): 
    return (sum(myl)+0.0) / len(myl)  # + 0.0 needed in 2.x to make it a float

def readNumbersFromFile( filename ):
    '''Function that takes a filepath and parses it. The file is required to 
    consist out of integer numbers only - text or floating point numbers
    are not handled and lead to exceptions. The file format allows for 
    multiple integer numbers seperated by spaces per line and for multiple
    lines and will parse all numbers into one flat list and return it.'''    
    numbersFile = open (filename, 'r') # open file for read
    allNumbers = [] # result list

    for line in numbersFile: # reads one line
        for number in line.split(" "): # splits one line into single numbers
            allNumbers.append(int(number)) # adds each number as integer to list

    return allNumbers # returns the list from this function

nums = readNumbersFromFile(r'numbers.dat')

print("The average is ", avg(nums)) 

My avg-computing uses the build-in sum - you could also compute the avg yourself by adding all elements in the list and dividing by the amount of items in the list

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • @yacc I am all in for solutions that teach something. Thats why I use an approch likely to be understood (not using statistics) and comment what the lines do so it is understandable. Finding duplicates is preffered though. thats why i linked the question pertaining to avg of lists. did not check for the whole question though. – Patrick Artner Dec 09 '17 at 11:08
  • 1
    @yacc thanks for pointing that out. added summarization of what it does – Patrick Artner Dec 09 '17 at 11:31
0

this works :

S = open("numbers.dat").read()
from statistics import mean
print(mean(map(int,S.split())))

how it works:

  • open file, read content
  • split content into pieces using space as default separator
  • apply conversion to integer to each piece
  • compute mean using statistics module
Setop
  • 2,262
  • 13
  • 28
  • 1
    @yacc, your right. I had the same thinking reviewing my answer : a bit rude for someone starting python, so I added some explanations – Setop Dec 09 '17 at 11:06