Introduction to Discrete Mathematics

Sets

Notes By Pr. El Hadiq Zouhair

1 / 13

Overview

Python / SymPy — imports (run once) from sympy import FiniteSet, EmptySet, Integers, Naturals0, Rationals, Reals, Complexes from sympy import Symbol, Interval, Union, Intersection, Complement, ProductSet from itertools import chain, combinations, product
2 / 13

Definition

A set is a finite or infinite collection of elements without order and without multiplicity:

$\{1,\, 1,\, 3,\, 9\} = \{1,\, 3,\, 9\}$

A list (Python list) is an ordered collection that allows duplicates.

Python data = [1, 3, 9, "a", (1, "b"), 1, 4] unique_sorted = sorted(set(data), key=str) print(unique_sorted)
SymPy S = FiniteSet(1, 3, 9, 1, 4) print(S) # {1, 3, 4, 9} print(len(S)) # 4

Size (Cardinality)

The size (or cardinality) of a set is the number of elements it contains: $|S|$.

Python S = {1, 3, 9} print(len(S)) # 3 → |S| = 3
3 / 13

Important Sets

Python — finite empty = set() # ∅ evens = {0, 2, 4, 6, 8} # finite print(len(empty), len(evens))
SymPy — infinite from sympy import S S.Integers, S.Naturals0 S.Rationals, S.Reals, S.Complexes 2 in S.Integers # True
4 / 13

Countable and Uncountable

Any set that can be put in a one-to-one correspondence with the natural numbers is countable.

Python — enumerate Z (bijection with N) def enumerate_integers(n): # 0,1,-1,2,-2,3,-3,... return 0 if n == 0 else ((n + 1) // 2) * (1 if n % 2 else -1) print([enumerate_integers(k) for k in range(8)])
Output [0, 1, -1, 2, -2, 3, -3, 4]
Python — table p/q for Q from fractions import Fraction table = [[Fraction(p, q) for q in range(1, 6)] for p in range(1, 6)] for row in table: print(row)
5 / 13

Venn Diagram

Sets can be represented visually using Venn diagrams. Below: $A \cap B$ (orange region).

A B A∩B
Python — quick Venn with matplotlib_venn # pip install matplotlib matplotlib_venn from matplotlib_venn import venn2 import matplotlib.pyplot as plt A = {1, 2, 3, 4} B = {3, 4, 5, 6} venn2([A, B], set_labels=('A', 'B')) plt.show()
6 / 13

Subset

A subset ($\subset$, $\subseteq$) is a portion of a set. $A \subseteq B$ means every element of $A$ is in $B$.

Python — slice / subset test S = [2, 3, 4, 7, 10] print(S[2:4]) # [4, 7] A, B = {4, 7}, set(S) print(A.issubset(B)) # True print(A <= B, A < B) # True True
SymPy from sympy import FiniteSet A = FiniteSet(4, 7) B = FiniteSet(2, 3, 4, 7, 10) A.is_subset(B) # True

Power Set

The power set $\mathcal{P}(S)$ is the set of all subsets of $S$. If $|S| = n$, then $|\mathcal{P}(S)| = 2^n$.

Python — power set from itertools import chain, combinations def powerset(s): s = list(s) return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1))) print(powerset({2, 3, 4, 7, 10})) # 2**5 = 32 subsets
Output (32 subsets) [(), (2,), (3,), (4,), (7,), (10,), (2,3), (2,4), (2,7), (2,10), (3,4), (3,7), (3,10), (4,7), (4,10), (7,10), (2,3,4), (2,3,7), (2,3,10), (2,4,7), (2,4,10), (2,7,10), (3,4,7), (3,4,10), (3,7,10), (4,7,10), (2,3,4,7), (2,3,4,10), (2,3,7,10), (2,4,7,10), (3,4,7,10), (2,3,4,7,10)]
7 / 13

Partition

A set partition of $S$ is a collection of disjoint subsets of $S$ whose union is $S$.

Python — partition by chunks of size n def partition(seq, n): return [list(seq[i:i+n]) for i in range(0, len(seq), n)] print(partition(range(1, 19), 3))
Output [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]

A cover is the same idea but the subsets may overlap:

Python — overlapping windows (cover) def cover(seq, n, step): return [list(seq[i:i+n]) for i in range(0, len(seq)-n+1, step)] print(cover(range(1, 19), 4, 2))
Output [[1,2,3,4], [3,4,5,6], [5,6,7,8], [7,8,9,10], [9,10,11,12], [11,12,13,14], [13,14,15,16], [15,16,17,18]]
8 / 13

Cartesian Product

The Cartesian product of two sets $A$ and $B$ is the set of all ordered pairs $(a, b)$ with $a \in A$ and $b \in B$:

$A \times B = \{(a, b) \mid a \in A,\; b \in B\}$

Python — itertools.product from itertools import product A = [1, 3, 5, 7, 9] print(list(product(A, repeat=2))) # A × A
SymPy — ProductSet from sympy import FiniteSet, ProductSet A = FiniteSet(1, 3, 5, 7, 9) B = FiniteSet(2, 4) P = ProductSet(A, B) list(P) # [(1,2),(1,4),(3,2),...]

Association (dictionary)

An association is a mapping between keys and values. In Python this is the built-in dict:

Python — dict d = {"a": "x", "b": "y", "c": "z"} print(d["a"]) # 'x' print(list(d.keys()), list(d.values()))
9 / 13

Dataset

A dataset is a list of structured associations of attributes and data. In Python, this is naturally a list of dictionaries — or a pandas.DataFrame.

Python — list of dicts titanic = [ {"class": "1st", "age": 29, "sex": "female", "survived": True}, {"class": "1st", "age": 2, "sex": "female", "survived": True}, {"class": "1st", "age": 30, "sex": "male", "survived": False}, {"class": "3rd", "age": 27, "sex": "male", "survived": False}, {"class": "3rd", "age": 29, "sex": "male", "survived": False}, ] # survivors only print([row for row in titanic if row["survived"]])
Python — with pandas # pip install pandas import pandas as pd df = pd.DataFrame(titanic) print(df.head()) print(df.groupby("class")["survived"].mean())
The Mathematica ExampleData["Dataset","Titanic"] idea translates directly to a Python DataFrame — same tabular structure, same filtering, much faster on real data.
10 / 13

Empty Set

Often, there is a lot of confusion about the empty set $\varnothing = \{\}$.

Python — sizes print(len(set())) # 0 print(len({frozenset(), frozenset({frozenset()})})) # 2
Python — power sets def powerset(s): s = list(s) return [set(combinations(s, r)[0]) if False else c for r in range(len(s)+1) for c in combinations(s, r)] # P(∅) = {∅} print(list(powerset(set()))) # [()] # P(P(∅)) = {∅, {∅}} print(list(powerset(powerset(set())))) # [(), ((),)]
Python — Cartesian product with ∅ print(list(product(set(), {2, 4, 6, 8}))) # [] → ∅ × A = ∅
11 / 13

Summary

Python — key imports for this lesson from itertools import chain, combinations, product from fractions import Fraction from sympy import (FiniteSet, EmptySet, Integers, Naturals0, Rationals, Reals, Complexes, Interval, Union, Intersection, Complement, ProductSet)
12 / 13

Wolfram → Python Quick Reference

Operation Wolfram Python (built-in) SymPy
Set literal {1, 3, 9}{1, 3, 9}FiniteSet(1,3,9)
Empty set {}set()EmptySet
Size Length[S]len(S)len(S)
Unique + sort Sort@DeleteDuplicates[L]sorted(set(L))
Membership MemberQ[S, x]x in SS.contains(x)
Subset test SubsetQ[B, A]A <= BA.is_subset(B)
Power set Subsets[S]chain(combinations…)S.powerset()
Cartesian product Tuples[{A, B}]itertools.product(A, B)ProductSet(A, B)
Union Union[A, B]A | BUnion(A, B)
Intersection Intersection[A, B]A & BIntersection(A, B)
Difference Complement[A, B]A - BComplement(A, B)
Integers / Reals Integers, RealsS.Integers, S.Reals
Dictionary <|a → x|>{"a": "x"}
Dataset Dataset[…]list[dict] / pandas.DataFrame
13 / 13