Reputation: 99
So yesterday I finished up the code I designed which ask the school administrator how many students you want to track, their respective grades and most importantly what courses they took.
Thus giving me a code:
COLS= int(input("number of students to enter: "))
ROWS= int(input("number of grades per student: "))
number =[]
for c in range(COLS):
studentinfo=[]
student =(input("enter student Name: "))
studentinfo.append(student)
for r in range (ROWS):
course=input("Enter course Code: ")
studentinfo.append(course)
grades =float(input("Enter grade for module: "))
studentinfo.append(grades)
number.append(studentinfo)
print(number)
Which gives me a sample output of:
number of students to enter: 2
number of grades per student: 1
enter student Name: KenL
Enter course Code: MA344
Enter grade for module: 80
enter student Name: Harry
Enter course Code: PY101
Enter grade for module: 60
[['KenL', 'MA344', 80.0], ['Harry', 'PY101', 60.0]]
Now the idea is with that current output, I Want to create a function which would take the student list and course code and returns a new list which contains the names of students from the students list that have a grade higher than the average in course code.
For example: above_avg(number,"MA22") returns a list of the names of students who perform better than average in MA22.
I've started of by writting this code down:
lookup=input("Which course code do you want to lookup: ")
def find_above_avg(number,lookup):
if lk in number:
avg=...
If anyone has any suggestions as to how I may alter the code I have so I can perform the look-up it would be greatly appreciated.
Upvotes: 0
Views: 115
Reputation: 3647
Well, you can make it work with lists.
First, we can try selecting students that took a given lecture:
def select_by_course(list_of_students, course):
return [student for student in list_of_students if student[1] == course]
It's also easy to find the average:
def average_grade(list_of_students, course):
grades = [grade for (name, code, grade) in list_of_students if code == course]
return sum(grades) / len(grades)
Then, we realize that it's not too difficult to do what you want:
def find_above_average(list_of_students, course):
relevant_students = select_by_course(list_of_students, course)
average = average_grade(relevant_students, course)
return [student for student in relevant_students if student[2] > average]
Here, we're doing it in three loops (one on the whole data and two on the relevant students), you can do it in two if you want (try it).
Upvotes: 0
Reputation: 2567
l = [['KenL', 'MA344', 80.0], ['Harry', 'PY101', 60.0]]
lookup=raw_input("Which course code do you want to lookup: ")
avg = 60
def find_above_avg(number):
return [i for i in l if lookup in i and i[2] > avg]
print find_above_avg(avg)
Output:
Which course code do you want to lookup: MA344
[['KenL', 'MA344', 80.0]]
Upvotes: 1