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 trialKristian Vrgoc
3,046 PointsSets.py, Task 2 of 2: understanding the if statement.
Hey Guys,
I got the solution on the forum. I understand what the if statement is doing, but why in this way? My comments are added in the code.
Kind regards
Kristian
COURSES = {
"Python Basics": {"Python", "functions", "variables",
"booleans", "integers", "floats",
"arrays", "strings", "exceptions",
"conditions", "input", "loops"},
"Java Basics": {"Java", "strings", "variables",
"input", "exceptions", "integers",
"booleans", "loops"},
"PHP Basics": {"PHP", "variables", "conditions",
"integers", "floats", "strings",
"booleans", "HTML"},
"Ruby Basics": {"Ruby", "strings", "floats",
"integers", "conditions",
"functions", "input"}
}
def covers(arg):
course_list = []
for key, value in COURSES.items():
if value.intersection(arg):
course_list.append(key)
return course_list
def covers_all(arg):
name_list = []
for keys, values in COURSES.items():
if len(arg & values) == len(arg): # The outcome is always == len(arg), right? Like a infinite while loop?
name_list.append(keys) # Therefore it is like a trick to get to the goal, am I getting this right?
return name_list
3 Answers
Steven Parker
231,236 PointsThe outcome of "len(arg & values)
" would only be the same as "len(arg)
" when every item in "arg" was contained in "values". That's the point, to be sure that it "covers all". If it only covers some items, the lengths would differ.
This could also be done in a similar way to the first task by using "issubset" instead of "intersection".
Dave StSomeWhere
19,870 PointsYour first comment is incorrect, the length of the intersection of the arg and values will only be equal to the len of arg if all entries in arg are in the values variable. Basically this is verifying that all the topics exist in the course.
def covers_all(arg):
name_list = []
for keys, values in COURSES.items():
if len(arg & values) == len(arg): # The outcome is always == len(arg), right? Like a infinite while loop?
name_list.append(keys) # Therefore it is like a trick to get to the goal, am I getting this right?
return name_list
Does that help, Dave
Kristian Vrgoc
3,046 PointsThanks ! I got it :-)
Steven Parker
231,236 PointsKristian Vrgoc — Glad to help. You can mark the question solved by choosing a "best answer".
And happy coding!