Exercises — Sets & Frozensets
Exercise 4.5.1 Beginner
Section titled “Exercise 4.5.1 Beginner”Given a list, return a new list with all duplicate values removed. Order does not need to be preserved.
data = [4, 2, 7, 2, 1, 4, 9, 7]# expected (any order): [1, 2, 4, 7, 9]Exercise 4.5.2 Beginner
Section titled “Exercise 4.5.2 Beginner”Given two lists, return the elements that appear in both (intersection), as a set.
a = [1, 2, 3, 4, 5]b = [4, 5, 6, 7, 8]# expected: {4, 5}Exercise 4.5.3 Intermediate
Section titled “Exercise 4.5.3 Intermediate”Given two lists, return the elements that appear in either but not both (symmetric difference), sorted ascending.
a = [1, 2, 3, 4]b = [3, 4, 5, 6]# expected: [1, 2, 5, 6]Exercise 4.5.4 Intermediate
Section titled “Exercise 4.5.4 Intermediate”Given a string, return True if it contains only unique characters (no character appears more than once).
is_unique("abcde") # Trueis_unique("hello") # False — "l" appears twiceExercise 4.5.5 Intermediate
Section titled “Exercise 4.5.5 Intermediate”Given a list of lists, return a list of frozensets representing each inner list. Then find which frozenset elements are common to all inner lists.
groups = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]# frozensets: {1,2,3}, {2,3,4}, {3,4,5}# common to all: frozenset({3})Exercise 4.5.6 Advanced
Section titled “Exercise 4.5.6 Advanced”Given a list of sets, return the union of all sets without using a loop (use functools.reduce or the unpacking operator).
from functools import reducesets = [{1, 2}, {3, 4}, {2, 5}]# expected: {1, 2, 3, 4, 5}