Students in a course are given three attempts for a quiz. And their final score
ID: 3700799 • Letter: S
Question
Students in a course are given three attempts for a quiz. And their final score is computed by selecting their maximum score out of the three attempts. Write a program that reads in the students scores for the different quiz attempts from a file, and print out the final grade for each student. You MUST use a hash/dictionary as the student IDs are not sequential numeric values.
The file format is:
STD_ID<tab>ATTEMPT_NUM<tab>SCORE
Use the attached score file to test your code.
Your solution must include:
1. PAC
2. Algorithm
3. Python Code
Explanation / Answer
'''
Algorithm:
STEP 0: Open a file and readline
STEP 1: repeat step 2 to STEP 7 until file is read
STEP 2: check for if all the three values are there in the line then GOTO STEP 3 else GOTO STEP 8
STEP 3: SET sid as values[0] , ATTEMPT AS values[1] ,SCORE as values[2]
STEP 4: check if an error is getting while accessing SID in dictionary if no error GOTO 5 else GOTO 6
STEP 5: check student previous score is < current score IF yes replace previous score with current score
STEP 6: create a new key with SID and value with SCORE
STEP 7: read next line GOTO STEP 1
STEP 8: print missing details and goto STEP 7
STEP 9: FINALLY PRINT STUDENT ID AND CORRESPONDING MAXIMUM OF THREE TESTS
'''
'''
WRITTEN IN PYTHON 2.7
SAMPLE TEST FILE:
13 1 20
1 1 4
2 1 5
1 2 10
1 3 25
'''
f = open("file.txt","r") #open the input file
x = f.readline() #read line
student = {} #dictionary which contains student id and maximum marks
while(x):
try:
values = x.split(" ") #split line
if(len(values)!=3): #if there are not 3 values do nothing
print "Missing some values of student"
else: #if there are 3 values
sid = int(values[0].strip()) #sid,attempt,score
attempt = int(values[1].strip())
score = int(values[2].strip())
try:
if(student[sid]<score): #if sid is already in dictionary check for maximum score between current and previous
student[sid] = score #replace previous score with current score
except KeyError:
student[sid] = score #if sid is not there insert new sid and score
except Exception:
print "Error reading student details"
x = f.readline() #read next line
keys = student.keys()
val = student.values()
for i in xrange(len(keys)):
print keys[i],"=",val[i]