Python Python Collections Dictionaries Teacher Stats

Challenge 4 - most_courses

Some one can help me why my code it not pass in this challenge

def most_courses(a):
     teacher = ""
     max_count = 0
    for t,c in a.items():
         if len(c) > max_count:
                teacher = t
                max_count = len(c)
    return teacher
teachers.py
# The dictionary will look something like:
# {'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],
#  'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Each key will be a Teacher and the value will be a list of courses.
#
# Your code goes below here.

def most_courses(a):
    teacher = ""
    max_count = 0
    for t,c in a.items():
        if len(c) > max_count:
            teacher = t
            max_count = len(c)
    return teacher, max_count

2 Answers

Steven Parker
Steven Parker
168,640 Points

Both of these are very close!

The first example would be correct except that it has inconsistent indentation.

The second example is returning a tuple instead of just the name of the teacher.

Andrew Bickham
Andrew Bickham
Pro Student 792 Points

if it is okay I just have a quick question. my question is, if the challenge is to return the name of the teacher with the most courses and both teachers have the same amount of courses, why must you add a condition to the code? couldn't you just store the name of the teachers in a variable and then return that variable? i must be missing something. but i hope my question made sense and i hear from you soon.

Steven Parker
Steven Parker
168,640 Points

Cao Tru's code does store the name in the variable "teacher" and then return it. The condition is used to find the teacher associated with the list with the most courses. You can expect that unlike the sample in the comments, the actual test data will not have the same number of courses for every teacher.

Andrew Bickham
Andrew Bickham
Pro Student 792 Points

one more question, as of now, but why is max count equal to 0? is it because we don't know how many courses the actual test data might be? or is it because of some other reason? to me its just weird that the max_count of something would be equal to 0

Steven Parker
Steven Parker
168,640 Points

It's only 0 to begin with. Each time the loop finds a list with a larger count, it gets updated to the larger number.

Thanks everyone i passed challenge. I don't know why, when i retyping and check botton it's passed. Thanks your support!

Steven Parker
Steven Parker
168,640 Points

Cao Tru — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!