For Loops vs. List Comprehension Examples In this notebook, we will look at many of the exercises that you saw in Notebook 1. The exercises could be answered with list comprehensions or for loops.


In [ ]:
grades = [
    # First line is descriptive header. Subsequent lines hold data
    ['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
    ['Thorny', '100', '90', '80'],
    ['Mac', '88', '99', '111'],
    ['Farva', '45', '56', '67'],
    ['Rabbit', '59', '61', '67'],
    ['Ursula', '73', '79', '83'],
    ['Foster', '89', '97', '101']
]

Exercise 0 (students_test: 1 point). Write some code that computes a new list named students[:], which holds the names of the students as they from "top to bottom" in the table.


In [ ]:
### BEGIN SOLUTION (LIST COMPREHENSION)
students = [L[0] for L in grades[1:]]
### END SOLUTION

In [ ]:
### BEGIN SOLUTION (FOR LOOP)
students = []
for x in range (1, len(grades)):
    students.append(grades[x][0])
### END SOLUTION

In [ ]:
# `students_test`: Test cell
print(students)
assert type(students) is list
assert students == ['Thorny', 'Mac', 'Farva', 'Rabbit', 'Ursula', 'Foster']
print("\n(Passed!)")

Exercise 1 (assignments_test: 1 point). Write some code to compute a new list named assignments[:], to hold the names of the class assignments. (These appear in the descriptive header element of grades.)


In [ ]:
### BEGIN SOLUTION
assignments = grades[0][1:]
### END SOLUTION

Exercise 2 (grade_lists_test: 1 point). Write some code to compute a new dictionary, named grade_lists, that maps names of students to lists of their exam grades. The grades should be converted from strings to integers. For instance, grade_lists['Thorny'] == [100, 90, 80].


In [ ]:
# Create a dict mapping names to lists of grades.
### BEGIN SOLUTION (LIST COMPREHENSIONS)
grade_lists = {L[0]: [int(g) for g in L[1:]] for L in grades[1:]}
### END SOLUTION

In [ ]:
### BEGIN SOLUTION (FOR LOOP)
grade_lists = {}
for x in range (1, len(grades)):
    stu_grades = []
    for y in range(1, len(grades[x])):
        stu_grades.append(int(grades[x][y]))
    grade_lists[grades[x][0]] = stu_grades
### END SOLUTION

In [ ]:
# `grade_lists_test`: Test cell
print(grade_lists)
assert type(grade_lists) is dict, "Did not create a dictionary."
assert len(grade_lists) == len(grades)-1, "Dictionary has the wrong number of entries."
assert {'Thorny', 'Mac', 'Farva', 'Rabbit', 'Ursula', 'Foster'} == set(grade_lists.keys()), "Dictionary has the wrong keys."
assert grade_lists['Thorny'] == [100, 90, 80], 'Wrong grades for: Thorny'
assert grade_lists['Mac'] == [88, 99, 111], 'Wrong grades for: Mac'
assert grade_lists['Farva'] == [45, 56, 67], 'Wrong grades for: Farva'
assert grade_lists['Rabbit'] == [59, 61, 67], 'Wrong grades for: Rabbit'
assert grade_lists['Ursula'] == [73, 79, 83], 'Wrong grades for: Ursula'
assert grade_lists['Foster'] == [89, 97, 101], 'Wrong grades for: Foster'
print("\n(Passed!)")

Exercise 3 (grade_dicts_test: 2 points). Write some code to compute a new dictionary, grade_dicts, that maps names of students to dictionaries containing their scores. Each entry of this scores dictionary should be keyed on assignment name and hold the corresponding grade as an integer. For instance, grade_dicts['Thorny']['Exam 1'] == 100.


In [ ]:
# Create a dict mapping names to dictionaries of grades.
### BEGIN SOLUTION (LIST COMPREHENSION)
grade_dicts = {L[0]: dict(zip(assignments, [int(g) for g in L[1:]])) for L in grades[1:]}
### END SOLUTION

In [ ]:
# Create a dict mapping names to dictionaries of grades.
### BEGIN SOLUTION (FOR LOOP)
grade_dicts = {}
for x in range(1, len(grades)):
    stu_grades = []
    for y in range(1, len(grades[x])):
        stu_grades.append(int(grades[x][y]))
    grade_dicts[grades[x][0]] = dict(zip(assignments, stu_grades))
### END SOLUTION

In [ ]:
# `grade_dicts_test`: Test cell
print(grade_dicts)
assert type(grade_dicts) is dict, "Did not create a dictionary."
assert len(grade_dicts) == len(grades)-1, "Dictionary has the wrong number of entries."
assert {'Thorny', 'Mac', 'Farva', 'Rabbit', 'Ursula', 'Foster'} == set(grade_dicts.keys()), "Dictionary has the wrong keys."
assert grade_dicts['Foster']['Exam 1'] == 89, 'Wrong score'
assert grade_dicts['Foster']['Exam 3'] == 101, 'Wrong score'
assert grade_dicts['Foster']['Exam 2'] == 97, 'Wrong score'
assert grade_dicts['Ursula']['Exam 1'] == 73, 'Wrong score'
assert grade_dicts['Ursula']['Exam 3'] == 83, 'Wrong score'
assert grade_dicts['Ursula']['Exam 2'] == 79, 'Wrong score'
assert grade_dicts['Rabbit']['Exam 1'] == 59, 'Wrong score'
assert grade_dicts['Rabbit']['Exam 3'] == 67, 'Wrong score'
assert grade_dicts['Rabbit']['Exam 2'] == 61, 'Wrong score'
assert grade_dicts['Mac']['Exam 1'] == 88, 'Wrong score'
assert grade_dicts['Mac']['Exam 3'] == 111, 'Wrong score'
assert grade_dicts['Mac']['Exam 2'] == 99, 'Wrong score'
assert grade_dicts['Farva']['Exam 1'] == 45, 'Wrong score'
assert grade_dicts['Farva']['Exam 3'] == 67, 'Wrong score'
assert grade_dicts['Farva']['Exam 2'] == 56, 'Wrong score'
assert grade_dicts['Thorny']['Exam 1'] == 100, 'Wrong score'
assert grade_dicts['Thorny']['Exam 3'] == 80, 'Wrong score'
assert grade_dicts['Thorny']['Exam 2'] == 90, 'Wrong score'
print("\n(Passed!)")

Exercise 5 (grades_by_assignment_test: 2 points). Write some code to compute a dictionary named grades_by_assignment, whose keys are assignment (exam) names and whose values are lists of scores over all students on that assignment. For instance, grades_by_assignment['Exam 1'] == [100, 88, 45, 59, 73, 89].


In [ ]:
### BEGIN SOLUTION (LIST COMPREHENSION)
grades_by_assignment = {a: [int(L[k]) for L in grades[1:]] for k, a in zip(range(1, 4), assignments)}
### END SOLUTION

In [ ]:
### BEGIN SOLUTION (FOR LOOP)
grades_by_assignment = {}
for k in range(0, len(assignments)): #1,2,3
    stu_assignment = []
    for m in range(1,len(grades)):
        stu_assignment.append(int(grades[m][k+1]))
    grades_by_assignment[assignments[k]] = stu_assignment
### END SOLUTION

In [ ]:
# `grades_by_assignment_test`: Test cell
print(grades_by_assignment)
assert type(grades_by_assignment) is dict, "Output is not a dictionary."
assert len(grades_by_assignment) == 3, "Wrong number of assignments."
assert grades_by_assignment['Exam 1'] == [100, 88, 45, 59, 73, 89], 'Wrong grades list'
assert grades_by_assignment['Exam 3'] == [80, 111, 67, 67, 83, 101], 'Wrong grades list'
assert grades_by_assignment['Exam 2'] == [90, 99, 56, 61, 79, 97], 'Wrong grades list'
print("\n(Passed!)")

In [ ]: