Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHenry Lin
11,636 PointsIs there any other efficient way to solve this challenge? How do get a key if an index of a dictionary is given?
Hello guys, The following code is what I came out for this assignment (most_courses function), however, there are too many for loop involved which makes the programming super not efficient? I would like to know another efficient way to do it. And also, I was trying to get the index of the item that I converted from a dictionary's values and use the index to find the key, however, I stuck on that.
# 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 num_teachers(args):
return len(args)
def num_courses(args):
return sum(len(v) for v in args.values())
def courses(args):
new_list = []
for my_list in args.values():
new_list += my_list
return new_list
def most_courses(args):
course_list = []
max_count = 0
for course in args.values():
course_list_len += [len(course)]
for num in course_list_len:
if num > max_count:
max_count = num
'''else:
my_index = course_list_len.index(num)'''
for teacher in args:
if max_count == len(args[teacher]):
return teacher
1 Answer
Steven Parker
231,248 PointsYou might have gotten off track after the first loop.
As a hint, I'll say that you can can do this task with only one loop, and the loop would need only about 3 lines of code including a conditional. In addition to max_count you would need another variable to store which teacher goes with that count, and then after the loop finishes you would return that teacher.
Henry Lin
11,636 PointsHenry Lin
11,636 Pointsby the way, my function of most_courses didn't pass the challenge, but it worked fine on the workspace. I can't tell where I did wrong.
Steven Parker
231,248 PointsSteven Parker
231,248 PointsRemember that the challenge isn't just about creating code that runs. It must also serve a specific purpose. When you work externally you may not be testing for purpose with the same stringency that the challenge does.
Think about my hint, and see if you can create a more compact function. It may also be more likely to pass.