Set Operations · Exercises
Beginner

Set Operations Exercises

4 exercises that build on the Python Set Operations lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Set operations answer questions about whole groups in one step: union, intersection, difference and symmetric difference build new sets, subset and disjoint tests give yes/no answers, and the in-place versions update a set directly. By the end you can combine and compare sets with operators and methods, test subset and disjoint, update a set in place, use frozenset, write set comprehensions, and remove duplicates while keeping order. You will practise: Who has not handed in homework?; Predict the set answers; Fix the order of the unique items; Summarise the tags of several posts.

0 / 4 completed

Set Operations practice exercises

1. Who has not handed in homework?

Write code Easy

Complete missing_homework(enrolled, submitted). Both arguments are lists of names, and they may contain repeats. Return a sorted list of the students who are enrolled but have not submitted. A name in submitted that is not enrolled must be ignored.

Your code
def missing_homework(enrolled, submitted):
    # return a sorted list of enrolled students who did not submit
    pass

print(missing_homework(["Asha", "Ben", "Cara", "Dev"], ["Ben", "Dev", "Eli"]))

2. Predict the set answers

Predict the output Easy

Read the code and type exactly what it prints, line by line. Then press Check to run it and compare.

Read this code
a = {1, 2, 3, 4, 5}
b = {4, 5, 6}
print(sorted(a - b))
print(sorted(b - a))
print(sorted(a ^ b))
print(b <= a, {4, 5} <= b, a.isdisjoint({7, 8}))

3. Fix the order of the unique items

Fix the bug Medium

unique_in_order(items) should return the items without repeats, keeping the order in which each item first appeared. For [3, 1, 3, 2, 1] it should return [3, 1, 2], but the function returns the items in a different order. Fix it.

Your code
def unique_in_order(items):
    # keep the first appearance of each item, in the original order
    return list(set(items))

print(unique_in_order([3, 1, 3, 2, 1]))

4. Summarise the tags of several posts

Write code Hard

Write tag_summary(posts). posts is a list of sets of tags, one set per post. Return three sorted lists, in this order:

  1. tags that appear in every post,
  2. tags that appear in at least one post,
  3. tags that appear in exactly one post.

For an empty list of posts all three results are empty. Do not change the sets you receive.

Your code
def tag_summary(posts):
    # return (in_every_post, in_any_post, in_exactly_one_post) as sorted lists
    pass

posts = [{"python", "web"}, {"python", "data"}, {"python", "web", "api"}]
print(tag_summary(posts))

Next lessonPython Dictionaries

More Python Set Operations examples · All Python exercises