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 trialVictor Gavojdea
11,796 Pointsstepping into tuples
I don't know how to step into the nested 'prereqs' tuple to grab any of the titles, much less have it give me the 2nd one. I don't think Kenneth went over this in any of the videos prior to this. I hope I missed something. Very lost. Looking for help.
from operator import add
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()
if data.prereqs == None
#add(set, title)
#return prereqs(
2 Answers
Julian Garcia
18,380 PointsIt is a little tricky, because they never ask for example that you don't need include Django Basics. But if I think about it, it is not a prerequisite.
The solution I found was:
def prereqs(data, pres=None):
pres = pres or set()
if isinstance(data, list):
for item in data: #Sweep the list
pres.add(item['title']) #Add current item title
prereqs(item['prereqs'], pres) # The inner prereq are process in a recursive call to this method
else:
pres = prereqs(data['prereqs'], pres) #This is the initial point, Django Basics's prereqs, but this is not included in the answer
#We din't include data['title']
return pres
This code gives result in my terminal :
Flask Basics
Python Basics
Setting Up a Local Python Environment
Object-Oriented Python
Python Collections
Julian Garcia
18,380 PointsThe result is presented unordered that is because set is an unordered collection of unique elements. For example, if you put and text item in the set and continue adding more items and then you print the content of that set , the elements are not in the order you put it there.
Victor Gavojdea
11,796 PointsVictor Gavojdea
11,796 PointsThank you for the help. So then does item go down the tree? I thought it would stay at the first level.