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 trialfahad lashari
7,693 PointsIn task two I just hacked together whatever solution I possibly could. Is there any better solution to this?
The loop works great. I just feel though that this could be improved even more. Any pointers?
kind regards,
Fahad
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(topics):
list1 = []
for key, value in COURSES.items():
if topics.intersection(value):
list1.append(key)
return list1
def covers_all(topics):
list1 = []
for key, value in COURSES.items():
if not topics.difference(value):
list1.append(key)
return list1
1 Answer
leonardbode
Courses Plus Student 4,011 PointsFahad, you could use list comprehension.
def covers(topics):
return [key for key, value in COURSES.items() if topics.intersection(value)]
def covers_all(topics):
return [key for key, value in COURSES.items() if not topics.difference(value)]
fahad lashari
7,693 Pointsfahad lashari
7,693 PointsThanks! I never saw it from this angle. List comprehension still seems like a complete mystery to me. Any pointers for a good tutorial?
Kind regards,
Fahad
leonardbode
Courses Plus Student 4,011 Pointsleonardbode
Courses Plus Student 4,011 Pointshttps://www.youtube.com/watch?v=3dt4OGnU5sM>
Remember, list comprehension should only be used if this does not make the code harder to read.
PEP20: Simple is better than complex. Complex is better than complicated.
Most importantly: Readability counts.
Leo
fahad lashari
7,693 Pointsfahad lashari
7,693 PointsLeonard Bode
Cheers! I'll keep that in mind.
Have a great day =) !