On this page
Average Book Ratings
TIP101 Unit 2 Session 1 (Click for link to problem statements)
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What does the input look like?
- A dictionary that maps each book title to a list of its numeric ratings.
- What should the function return?
- A new dictionary that maps each book title to the average of its ratings.
- What if a book’s ratings list is empty?
- An empty list has no average, and
sum([]) / len([])would divide by zero and raiseZeroDivisionError. This solution handles that case defensively by giving the book an average of0.0. That is the same empty-input result the Calculate GPA problem in this session returns. The book still appears in the output.
- An empty list has no average, and
- What if the input dictionary is empty?
- Return an empty dictionary.
HAPPY CASE
Input: {"Book A": [5, 4, 3], "Book B": [4, 5]}
Output: {"Book A": 4.0, "Book B": 4.5}
Explanation: (5 + 4 + 3) / 3 = 4.0 and (4 + 5) / 2 = 4.5. Python's `/` always
returns a float, so a whole-number average prints as 4.0.
EDGE CASE
Input: {"Book C": []}
Output: {"Book C": 0.0}
Explanation: Book C has no ratings, so it gets the 0.0 fallback instead of
dividing by zero.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Loop through each book, find its average rating, and add the pair to a new dictionary.
1) Create an empty dict for average ratings
2) For each book and ratings list in the input dict
a) If the ratings list is empty, map book -> 0.0
(to prevent division by zero)
b) Otherwise, find the average of the ratings list
and map book -> average in the new average dict
3) Return the new average dict
⚠️ Common Mistakes
- Dividing by
len(ratings)without checking for an empty list first. A book with no ratings makes the divisor zero, and Python raisesZeroDivisionError.
I-mplement
def average_book_ratings(book_ratings):
avg_ratings = {}
for book, ratings in book_ratings.items():
if not ratings: # No ratings: avoid dividing by zero
avg_ratings[book] = 0.0
else:
avg_ratings[book] = sum(ratings) / len(ratings)
return avg_ratings