Equivalence Relations
An equivalence relation says when two things should be treated as "the same" for some purpose: two integers with the same remainder, two strings that are equal ignoring case, two files with the same content hash, two states of a game that look identical to the player. Every equivalence relation splits its set into disjoint groups, and conversely every split into groups defines an equivalence relation.
Definition
A relation on a set is an equivalence relation if it is
- reflexive: ,
- symmetric: ,
- transitive: .
Examples: equality; ; "has the same length" on strings; "is reachable in both directions" (strongly connected) on the vertices of a digraph; "" for any function .
The last example is universal: every equivalence relation has the form , where is the class of (see below).
Equivalence classes and partitions
The equivalence class of is .
Theorem. The equivalence classes of form a partition of : they are non-empty, every element is in one, and two classes are either equal or disjoint.
Proof. by reflexivity, so classes are non-empty and cover . Suppose and share an element : and . By symmetry and transitivity . Then any satisfies , so , and the same argument gives .
Conversely, a partition defines the relation "is in the same block as", which is an equivalence relation. The set of classes is written (the quotient).
from collections import defaultdict
def classes(A, key):
"""Group A by the function key: a ~ b iff key(a) == key(b)."""
groups = defaultdict(list)
for a in A:
groups[key(a)].append(a)
return dict(groups)
print("mod 4:", classes(range(-6, 10), lambda n: n % 4))
words = ["Listen", "silent", "enlist", "google", "banana", "Tinsel", "gogole"]
print("anagrams:", classes(words, lambda w: "".join(sorted(w.lower()))))mod 4: {2: [-6, -2, 2, 6], 3: [-5, -1, 3, 7], 0: [-4, 0, 4, 8], 1: [-3, 1, 5, 9]}
anagrams: {'eilnst': ['Listen', 'silent', 'enlist', 'Tinsel'], 'eggloo': ['google', 'gogole'], 'aaabnn': ['banana']}
Choosing a canonical representative per class (here, the remainder or the sorted letters) is how programs test equivalence quickly: two things are equivalent iff their canonical forms are equal.
Counting with classes
If every class has the same size , then the number of classes is . This is the division rule of counting. For example, there are ways to seat 5 people in a row, but around a round table rotations are considered the same; each class has 5 rotations, so there are circular seatings.
Union-find
When equivalences arrive one pair at a time ("these two accounts belong to the same person", "these two pixels have the same color and touch"), the union-find (disjoint-set) data structure maintains the partition. union(a, b) merges two classes, find(a) returns a class representative. With path compression and union by size each operation takes almost constant time. It is how Kruskal's minimum spanning tree algorithm (Kruskal) avoids cycles.
parent = {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
parent[x] = parent[parent[x]] # path compression (halving)
x = parent[x]
return x
def union(a, b):
parent[find(a)] = find(b)
same_person = [("ann@x.com", "ann@y.org"), ("bob@x.com", "robert@z.net"), ("ann@y.org", "a.smith@w.io")]
for a, b in same_person:
union(a, b)
emails = ["ann@x.com", "ann@y.org", "a.smith@w.io", "bob@x.com", "robert@z.net", "cid@x.com"]
groups = {}
for e in emails:
groups.setdefault(find(e), []).append(e)
print(list(groups.values()))[['ann@x.com', 'ann@y.org', 'a.smith@w.io'], ['bob@x.com', 'robert@z.net'], ['cid@x.com']]
In software
Equivalence classes appear as GROUP BY in SQL, as hash-based deduplication, as normalization (case folding, Unicode normalization, canonical JSON), as state minimization of finite automata, and as __eq__/__hash__ in Python: objects that compare equal must have equal hashes, which is precisely "".
Exercises
Exercise 1: Is it an equivalence?
On integers, which are equivalence relations? (a) iff is even; (b) iff ; (c) iff .
Answer
(a) yes; (b) no (not transitive); (c) yes.
Solution
(a) It is congruence mod 2: classes are the evens and the odds. (b) and but . (c) It has the form with ; classes are .
Exercise 2: Circular necklaces
How many ways are there to seat 6 people around a round table if only the cyclic order matters (rotations are the same)?
Answer
Solution
row arrangements; each circular seating corresponds to 6 rotations, all distinct because the people are distinct. .
Exercise 3: Group by a key (code)
Group the numbers 1 to 20 by their number of divisors. How many classes are there?
Answer
6 classes (divisor counts 1, 2, 3, 4, 5, 6).
Solution
from collections import defaultdict
ndiv = lambda n: sum(1 for d in range(1, n + 1) if n % d == 0)
g = defaultdict(list)
for n in range(1, 21):
g[ndiv(n)].append(n)
for k in sorted(g):
print(k, g[k])
print(len(g), "classes")1 [1]
2 [2, 3, 5, 7, 11, 13, 17, 19]
3 [4, 9]
4 [6, 8, 10, 14, 15]
5 [16]
6 [12, 18, 20]
6 classes
Test yourself
Which property is NOT required of an equivalence relation?
- reflexive
- symmetric
- antisymmetric
- transitive
Two equivalence classes and that share an element are…
- disjoint
- equal
- complements
- of different sizes
How many equivalence classes does congruence modulo 7 have on ?
- 6
- 7
- 8
- infinitely many