Reputation: 11
I am trying to get a working method in a class I have constructed. This class accumulates a given student's course history. Each course is a list (name, grade, credits, etc) that's part of the total list of all courses for that student. Here is an example course history:
[['English 1', 4, 3, 'Fall', '2009'],
['English 2', 3.7, 3, 'Spring', '2010'],
['English 3', 2.7, 3, 'Fall', '2010'],
['English 4', 3.0, 3, 'Spring', '2011'],
['English 5', 3.7, 3, 'Fall', '2011'],
['English 6', 3.3, 3, 'Spring', '2012'],
['Math 1', 3.3, 3, 'Fall', '2009'],
['Math 2', 2.7, 3, 'Spring', '2010'],
['Science 1', 3.7, 4, 'Fall', '2009'],
['Science 2', 4, 4, 'Spring', '2010']]
I can figure out cumulative GPA, but I am finding it hard to determine a semester GPA. Here is my relevant code:
class StudentInfo(object):
def __init__(self, last, first, dob):
self.last=last
self.first=first
self.dob=dob
self.gradehist=[]
def __add__(self, course):
return self.gradehist.append(course)
def cumulativegpa(self):
cred = [item[2] for item in self.gradehist]
grad = [item[1] for item in self.gradehist]
gc = [grad[i]*cred[i] for i in range(len(grad))]
hrs = sum(cred)
gpasum = sum(gc)
cumgpa = gpasum/hrs
return cumgpa
def semgpa(self, x, y):
semcred=[]
semgrad=[]
for i in self.gradehist:
if self.gradehist[3] == x and self.gradehist[4] == y:
semcred.append([item[2] for item in self.gradehist])
for i in self.gradehist:
if self.gradehist[3] == x and self.gradehist[4] == y:
semgrad.append([item[1] for item in self.gradehist])
return semcred, semgrad`
s1=StudentInfo('Bob','Dole', '1-1-1911')
s1 + ['English 1', 4, 3, 'Fall', '2009']
s1 + ['English 2', 3.7, 3, 'Spring', '2010']
etc
When I type s1.cumulativegpa() it returns the correct total gpa, but s1.semgpa('Fall','2009') returns "[],[]" Where am I going wrong?
edit: updated def semgpa(self, x, y):
to include
for course in self.gradehist:
if course[3] == x and course[4] == y:
semcred.append([item[2] for item in course])
Upvotes: 1
Views: 49
Reputation: 1436
I'm not sure if this is what you want, but you can try it like this:
def semgpa(self, x, y):
semcred=[]
semgrad=[]
for row in self.gradehist:
if row[3] == x and row[4] == y:
semcred.append(row[2])
semgrad.append(row[1])
return semcred, semgrad
First, you iterate over all rows. Then you only take the rows which belong to the selected semester. Then you can append the values from these rows to your new lists.
Upvotes: 0