0

QUESTION: Complete the following program, which reads in a file that has multiple grades, each separated by a comma, and prints out the computed average. That is, write the functions getGrades(): and calculateAverage():

def main():
  grades = getGrades()   #get the file name containing the grades
                         #and return the contents of the file
  avg = calculateAverage(grades) #separate the grades into numbers and compute
                         #the average
  print("The calculated average is:", avg)
main()

I have inserted the given function and wrote a new program, but I am little bit confused, also I am getting an error. Please help!

def getGrades():
  filename = input("Please enter a file name: ")
  openfile = open(filename, "r")
  readfile = openfile.readlines()

  return readfile

def calculateAverage(n):
  totalGrades = []

  for i in (n):
    Split = list(map(int, i.split(",")))
    totalGrades += Split

  avg = sum(totalGrades)/float(len(totalGrades))

  return avg

def main():
  grades = getGrades()                  
  avg = calculateAverage(grades) 
  print("The calculated average is:", avg)
main()
loveTrumpsHate
  • 601
  • 3
  • 11
  • 15
  • Smells homework. What kind of error are you getting? – koukouviou Mar 28 '15 at 20:52
  • error: readfile is not defined – loveTrumpsHate Mar 28 '15 at 20:52
  • 1
    Yes, it is a homework problem. But I am excessively trying myself. I just need little help. – loveTrumpsHate Mar 28 '15 at 20:54
  • In your getgrades function you should put the grades in a list and pass that to the other function – Daniel Mar 28 '15 at 20:58
  • If you're only entering a filename (and not a file path), the "open" function call is expecting the file to be in the same directory as your python script. Otherwise, you need to pass a path to the file. Are your script/file saved in the same directory? – Chris Noreikis Mar 28 '15 at 21:01
  • In your `calculateAverage` function you pass argument `n` and then you try to use the variable name of the previous function (`readfile`). Change `readfile` to whatever you pass as argument (here `n`). Besides that, your program has more problems but I guess your immediate problem is now solved, the rest are part of your HW. – koukouviou Mar 28 '15 at 21:03
  • modified my program according to your comments. Getting an error: "nsupported operand type(s) for /: 'list' and 'float'" – loveTrumpsHate Mar 28 '15 at 21:09
  • python 3.3 ......... – loveTrumpsHate Mar 28 '15 at 21:17

1 Answers1

0

In your calculateAverage() function, you pass the argument n but for the for loop you use the local variable name readfile of function getGrades().

Also, the result of split is a list of strings. To convert them to integers to perform the summations you can use map(). map returns an iterator that applies function to every item of iterable, yielding the results.

To remove newline and other whitespace from the lines you read you can use rstrip().

Finally, to perform a floating point division if both your arguments are integers you have to transform one of the two to a float. Check this answer.

The final program looks like this:

def getGrades():
  filename = input("Please enter a file name: ")
  openfile = open(filename, "r")
  readfile = openfile.readlines()

  return readfile

def calculateAverage(n):
  total_grades = []
  for i in (n):
    line_grade = list(map(int, i.rstrip().split(",")))
    total_grades += line_grade
  avg = sum(total_grades)/float(len(total_grades))
  return avg

def main():
  grades = getGrades()                  
  avg = calculateAverage(grades) 
  print("The calculated average is:", avg)

if __name__ == "__main__":
  main()

If you run this with a test file with contents: 5,10,15,20 you get:

>>> 
Please enter a file name: test.txt
The calculated average is: 12.5
>>> 

calculateAverage(n) without map() and with list comprehensions could be:

def calculateAverage(n):
  total_grades = []
  for i in (n):
    line_grade = i.rstrip().split(",")
    line_grade = [int(x) for x in line_grade]
    total_grades += line_grade
  avg = sum(total_grades)/float(len(total_grades))
  return avg

Finally you can do it the naive way and have a for loop for converting each element in the list returned by split to integer:

def calculateAverage(n):
  total_grades = []
  for i in (n):
    line_grade = i.rstrip().split(",")
    for element in line_grade:
      total_grades.append(int(element))
  avg = sum(total_grades)/float(len(total_grades))
  return avg
Community
  • 1
  • 1
koukouviou
  • 820
  • 13
  • 23