python - Read in a file that has multiple grades, each separated by a comma, and prints out the computed average -
question: complete following program, reads in file has multiple grades, each separated comma, , prints out computed average. is, write functions getgrades():
, calculateaverage():
def main(): grades = getgrades() #get file name containing grades #and return contents of file avg = calculateaverage(grades) #separate grades numbers , compute #the average print("the calculated average is:", avg) main()
i have inserted given function , wrote new program, little bit confused, getting error. please help!
def getgrades(): filename = input("please enter file name: ") openfile = open(filename, "r") readfile = openfile.readlines() return readfile def calculateaverage(n): totalgrades = [] 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()
in calculateaverage()
function, pass argument n
for
loop use local variable name readfile
of function getgrades()
.
also, result of split
list of strings. convert them integers perform summations can use map()
. map
returns iterator applies function every item of iterable, yielding results.
to remove newline , other whitespace lines read can use rstrip()
.
finally, perform floating point division if both arguments integers have transform 1 of 2 float
. check answer.
the final program looks this:
def getgrades(): filename = input("please enter file name: ") openfile = open(filename, "r") readfile = openfile.readlines() return readfile def calculateaverage(n): total_grades = [] 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 run test file contents: 5,10,15,20 get:
>>> please enter file name: test.txt calculated average is: 12.5 >>>
calculateaverage(n)
without map()
, list comprehensions be:
def calculateaverage(n): total_grades = [] in (n): line_grade = i.rstrip().split(",") line_grade = [int(x) x in line_grade] total_grades += line_grade avg = sum(total_grades)/float(len(total_grades)) return avg
finally can naive way , have loop converting each element in list returned split integer:
def calculateaverage(n): total_grades = [] in (n): line_grade = i.rstrip().split(",") element in line_grade: total_grades.append(int(element)) avg = sum(total_grades)/float(len(total_grades)) return avg
Comments
Post a Comment