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 trial

Python Functional Python The Lambda Lambada Recursion

Michael Christofersen
Michael Christofersen
4,453 Points

Why won't this accept my answer?

The challenge asks for a function to recursively list the prequisites to a class. My function is as follows: def prereqs(data, pres=None): pres = pres or set() add(pres, data['title']) for x in data['prereqs']: prereqs(x, pres) return pres

In my local environment I get this:

set(['Flask Basics', 'Python Collections', 'Object-Oriented Python', 'Python Basics', 'Setting Up a Local Python Environment', 'Django Basics'])

Why won't it accept my answer?

courses.py
courses = {'count': 2,
           'title': 'Django Basics',
           'prereqs': [{'count': 3,
                     'title': 'Object-Oriented Python',
                     'prereqs': [{'count': 1,
                               'title': 'Python Collections',
                               'prereqs': [{'count':0,
                                         'title': 'Python Basics',
                                         'prereqs': []}]},
                              {'count': 0,
                               'title': 'Python Basics',
                               'prereqs': []},
                              {'count': 0,
                               'title': 'Setting Up a Local Python Environment',
                               'prereqs': []}]},
                     {'count': 0,
                      'title': 'Flask Basics',
                      'prereqs': []}]}


def prereqs(data, pres=None):
    pres = pres or set()
    add(pres, data['title'])
    for x in data['prereqs']:
        prereqs(x, pres)
    return pres

2 Answers

Michael Christofersen
Michael Christofersen
4,453 Points

It didn't want the title for the first course. Fixed the code like this:

def prereqs(data, pres=None):
    pres = pres or set()
    for x in data['prereqs']:
        pres.add(x['title'])
        prereqs(x, pres)
    return pres

[Edit: updated format; moved to answer -cf]

I was banging my head against the wall for a while until I realised this, that it was only asking for the 'prerequisites', not all course titles.

Kevin Kirsche
Kevin Kirsche
9,588 Points

Thanks for this. For me, it was as simple as putting a return in front of prereqs(x, pres) in my equivalent code. Thanks for sharing / helping