Skip to content

Exercises — Sets & Frozensets

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]

▶ Try in Playground

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}

▶ Try in Playground

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]

▶ Try in Playground

Given a string, return True if it contains only unique characters (no character appears more than once).

is_unique("abcde") # True
is_unique("hello") # False — "l" appears twice

▶ Try in Playground

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})

▶ Try in Playground

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 reduce
sets = [{1, 2}, {3, 4}, {2, 5}]
# expected: {1, 2, 3, 4, 5}

▶ Try in Playground