Programming with Lists and Tuples Develop a Python program that will calculate a
ID: 3846724 • Letter: P
Question
Programming with Lists and Tuples Develop a Python program that will calculate and display information about exam scores for the students in a class, as described below. The program will read the file scores.txt (no error checking or prompting) Each line of the input file will represent one student and four exam scores, and will have the following format: Name (string, maximum of 20 characters: two words separated by one comma) Exam #x score (integer, range 0 to 100) The student's name will be in the first 20 characters of the line. The four exam scores will be separated by one or more blanks. For example: Hopper Grace 100 98 87 97 82 87 92 81 Knuth, Donald Goldberg Adele 94 96 90 91 89 74 89 77 Kernighan, Brian 87 97 81 85 Liskov, Barbara The program will assume that the input file contains no erroneous data. The program will read the contents of the input file and store the data set in a list of tuples, where each tuple will represent one student and will contain the following information: Name (str) Exam #1 score (int) Exam #2 score (int) Exam #3 score (int) Exam #4 score (int) Exam average (float) The type of each field within the tuple is listed: the student's name will be type str, the four exam scores will be type int, and the exam average will be type float.Explanation / Answer
import sys,os
name=''
ex1_score=0
ex2_score=0
ex3_score=0
ex4_score=0
avg_score=0.0
scores=[]
with open('scores.txt') as f:
for line in f:
temp_list=[]
name=line[0:18]
list=line[19:len(line)].split()
ex1_score=int(list[0])
ex2_score=int(list[1])
ex3_score=int(list[2])
ex4_score=int(list[3])
avg_score=float(float(ex1_score+ex2_score+ex3_score+ex4_score)/float(4))
temp_list.append(name)
temp_list.append(ex1_score)
temp_list.append(ex2_score)
temp_list.append(ex3_score)
temp_list.append(ex4_score)
temp_list.append(avg_score)
scores.append(tuple(temp_list))
scores=sorted(scores, key=lambda x: x[0])
print("{:20s}{:6s}{:6s}{:6s}{:6s}{:6s}".format("Name","Exam1","Exam2","Exam3","Exam4","Mean"))
ex1_mean=0
ex2_mean=0
ex3_mean=0
ex4_mean=0
for i in scores:
print("{:20s}{:6d}{:6d}{:6d}{:6d}{:10.2f}".format(i[0],i[1],i[2],i[3],i[4],i[5]))
ex1_mean=ex1_mean+i[1]
ex2_mean=ex2_mean+i[2]
ex3_mean=ex3_mean+i[3]
ex4_mean=ex4_mean+i[4]
ex1_mean=float(float(ex1_mean)/float(len(scores)))
ex2_mean=float(float(ex2_mean)/float(len(scores)))
ex3_mean=float(float(ex3_mean)/float(len(scores)))
ex4_mean=float(float(ex4_mean)/float(len(scores)))
print("{:22s}{:6s}{:6s}{:6s}{:6s}".format("Exam Mean",str(ex1_mean),str(ex2_mean),str(ex3_mean),str(ex4_mean)))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.