AR5618
AR5618

Reputation: 11

Average of numbers input from a text file

I am trying to find the mean of numbers in a list. I get the list from a .txt file and then put it through my function.

def find_mean(list):
 sumofnums = sum(list)
 avgofnums= sumofnums/len(list)
 print(avgofnums)



def get_numbers_from_file(file_name):
 file = open(file_name, "r")
 strnumbers = file.read().split()
 int_strnumbers = [int(i) for i in strnumbers
 return (int, int_strnumbers)



mylist = get_numbers_from_file(input("Enter file name"))
print(find_mean(mylist))

However, I get the operand type error i.e it says the file is returned as a list of strings not ints.

Traceback (most recent call last):
 File "C:/Users/andrewr/Desktop/Mean_Module.py", line 15, in <module>
  print(find_mean(mylist))
 File "C:/Users/andrewr/Desktop/Mean_Module.py", line 3, in find_mean
  sumofnums = sum(list)
TypeError: unsupported operand type(s) for +: 'int' and 'type'

I thought I solved this problem by changing strnumbers to int_strnumbers.

Please help can anyone help me?

Upvotes: 0

Views: 46

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

This line

return (int, int_strnumbers)

should just be

return int_strnumbers

However rather than reading the file line-by-line like this, I'd suggest you use numpy which will be much faster. For example reading the file into an array would be

numpy.genfromtxt(file_name, delimeter=' ')

Then to compute the average you use numpy.average

mean = numpy.average(numpy.genfromtxt(file_name, delimeter=' '))

Upvotes: 1

Related Questions