Python Python Collections Sets Set Math

This works in intelliJ but not in the brower. Please help

def covers(x): courselist=[] for k, values in COURSES.items(): if x.issubset(values): courselist.append(k) return courselist

sets.py
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(x):
    courselist=[]
    for k, values in COURSES.items():
        if x.issubset(values):
            courselist.append(k)
    return courselist

3 Answers

William Li
PRO
William Li
Pro Student 26,692 Points

Are you in part1? Part1 is looking for values overlap between x & COURSES. Your code is mostly correct, but you need to change the .issubset into .intersectionn method. That should fix the prob.

Also, you can simplify the code by making use of Python's list comprehension.

def covers(x):
    return [key for key in COURSES if x.intersection(COURSES[key])]

That's another way to solve part 1. hope that helps, happy coding.

Thanks William for your quick reply. Appreciate the tip! List comprehension is a cool feature. But is this generally a good practice? I am not sure if it would affect things like refactoring and of course when passing on your scripts forward to another programmer. Is this an explicit/implicit methodology question?

William Li
William Li
Pro Student 26,692 Points

For this particular problem, list comprehension approach is better. But not because it's a one-liner, your code gets better performance by using list comprehension because it doesn't need to load & call the append() function each time the conditional is true. If COURSES happens to be a large dataset, the performance difference becomes very apparent. Python has many functional tools built-in, choosing the right tools for the job is the key to writing clean code.

ahh, i get it. Thanks William!