Lesson 4 of 15

Set Theory

Sets: The Foundation of Mathematics

A set is an unordered collection of distinct objects. Sets are described by membership: xAx \in A means xx belongs to AA.

Key Operations

OperationNotationDefinition
UnionABA \cup B{x:xA or xB}\{x : x \in A \text{ or } x \in B\}
IntersectionABA \cap B{x:xA and xB}\{x : x \in A \text{ and } x \in B\}
DifferenceABA \setminus B{x:xA and xB}\{x : x \in A \text{ and } x \notin B\}
ComplementAcA^c{xU:xA}\{x \in U : x \notin A\}
Power setP(A)\mathcal{P}(A)Set of all subsets of AA
Cartesian productA×BA \times B{(a,b):aA,bB}\{(a,b) : a \in A, b \in B\}

Power Set

If A=n|A| = n, then P(A)=2n|\mathcal{P}(A)| = 2^n. Every element either is or isn't in a subset — nn binary choices.

def power_set(s):
    result = [frozenset()]
    for elem in sorted(s):
        result = result + [subset | {elem} for subset in result]
    return result

print(len(power_set({1, 2, 3})))  # 8 = 2^3

Cartesian Product

A×B=AB|A \times B| = |A| \cdot |B| — the product rule for counting.

def cartesian_product(A, B):
    return [(a, b) for a in sorted(A) for b in sorted(B)]

print(len(cartesian_product({1, 2}, {3, 4, 5})))  # 6 = 2 × 3

Your Task

Implement power_set(s) and cartesian_product(A, B) as shown above.

Pyodide loading...
Loading...
Click "Run" to execute your code.