Sets, functions and cardinality
Review naive set theory, functions and their properties, images and preimages. Develop infinite cardinality and Cantor's diagonal argument, which reappears in the halting problem's undecidability.
After this lesson you can
- Manipulate set operations, Cartesian products, and power sets and prove identities by double inclusion.
- Classify functions as injective, surjective, or bijective and reason about composition and inverses.
- Calculate images and preimages and determine which commute with unions, intersections, and complements.
- Construct explicit bijections, including Cantor pairing, and prove countability.
- Apply diagonalization to prove |A| < |P(A)| and that noncomputable functions exist.
Before you start
Motivation: there are more problems than programs
A program is finite text. A property of programs (“this code never writes outside a buffer,” “this function always terminates,” “this model never returns personal data”) is a set of texts: those satisfying it. This lesson ends by proving there are strictly more sets of texts than texts, and therefore strictly more properties than programs able to decide them. Almost all properties, in a sense we will specify, are decided by no program.
This is not merely a logician’s curiosity. It directly affects what you can build:
- Program analysis. No static-analysis tool can exactly decide a nontrivial property of program behavior: the Rice theorem states this, proven by reduction to the halting problem, whose undecidability is this lesson’s diagonal argument applied to programs. Real tools therefore approximate: they either warn too much (false positives) or miss too much (false negatives); choosing which error to accept is a design decision, not a defect fixed with more engineering.
- Machine learning. With fixed architecture, a network with
float32parameters has only possible parameter values, so represents at most functions. There are Boolean functions of input bits. Representing all requires : with 64-bit inputs, over parameters. This is a finite cardinality argument like this lesson’s, and a fundamental reason learning needs assumptions about the target function. - Probability. A random variable is a function , and event “ falls in ” is set , the preimage of . Measure theory rests on an elementary property proven here: preimages preserve unions, intersections, and complements.
We need mathematics’ common language: sets, functions between sets, and a way to compare sizes that works for infinite sets. Much is review, but with a stronger requirement than you may have met before: prove every identity, write every definition with quantifiers, and support every infinity claim with an explicit executable bijection.
Sets
Membership, inclusion, and extensionality
We use naive set theory: a set is a collection of objects, its elements, and only which elements it has matters. Write for “ belongs to .” Sets are equal if they have the same elements, regardless of order or repetition: . This is extensionality, written in predicate logic as
is a subset of , , if . Extensionality is equivalent to double inclusion: iff and . This is the standard method for proving set equality: take an arbitrary element of one and show it belongs to the other, then reverse.
Do not confuse two relations: relates an element to a set, relates two sets. With , and , but , , and . The empty set is a subset of every set (implication is vacuously true) but not an element of every set: and , whereas .
Sets are described by enumeration, , or comprehension: is the set of elements of satisfying formula . We use , including zero as in Python, and , , with usual meanings.
Operations
The final column is key. Each Boolean set operation is a logical connective applied to “ belongs”: means , and likewise. Expression corresponds to formula , with short for . A point of the universe “sees” only three bits about the sets, whether it is in , , and , and those bits decide membership in the expression. Points with the same three bits form a Venn diagram region: , one per truth-table row.
The figure illustrates a theorem worth proving because it makes every set identity a mechanical calculation.
Identities: double inclusion and truth tables
Proof
(2) ⟹ (1). By induction on the expression, iff is true under the valuation assigning each letter the truth value of . Equivalent formulas agree under every valuation, so for every , ; extensionality gives .
(1) ⟹ (2). By contraposition. If and are not equivalent, some valuation makes them differ. Take a one-point universe and define if is true, otherwise . Then lies in ‘s region, and and have the distinct values of and under : .
(2) ⟺ (3). Regions are exactly valuations, and an expression contains a region iff its formula is true under that valuation.
∎The proof of says more: any failed identity already fails in a one-element universe. This is exactly the figure’s counterexample. The theorem also yields a count: an expression is determined by its regions, so letters give exactly distinct expressions up to equality: 256 with three sets and 65,536 with four. They are the same as Boolean functions of variables, not coincidentally: they are the same object.
A truth table decides but does not explain. Double inclusion does, and is the format used in texts. Example with a De Morgan law:
Double inclusion stops being a formality when each direction needs a different argument, as soon as functions or infinite quantifiers enter. We will see this with the image of an intersection.
Families, Cartesian products, and power sets
Operations extend to arbitrary families. If is a family indexed by set , finite or not,
Union is existential quantification and intersection universal, so quantifier laws give generalized De Morgan laws, and , because . For example : no belongs to every interval, since one can take . An intersection of a decreasing family of nonempty intervals can be empty, impossible for a finite family.
The Cartesian product is the set of ordered pairs, and iff and . For finite and , , where counts elements. The power set contains all subsets of ; its elements are sets, where and are often confused: means .
Proof
Every subset is determined by indicator , 1 on elements of and 0 elsewhere, and every function indicates exactly one subset: elements where it is 1. There are functions from an -element set to because each element independently chooses its value.
∎The correspondence between and , functions from to , does not require finite . With it identifies subsets of with infinite zero-one sequences, central to diagonalization. This is also how sets are stored as bit masks: integer 0b1011 represents .
Russell’s paradox and why ZFC exists
Unrestricted comprehension, “for each property the set exists,” seems harmless but is contradictory. Take property and set . Then
a contradiction. There is no hidden subtlety: this is the same structure as the diagonal argument at the lesson’s end, not by chance.
Mathematics adopted Zermelo–Fraenkel set theory with the axiom of choice, ZFC. We will not develop its axioms, but the idea defusing the paradox: separation allows only , selecting from an existing set . Applying Russell’s construction inside , , the same reasoning yields a theorem rather than contradiction: . No set contains all sets, and “the set of all sets” does not exist. Other axioms ensure practical sets exist: pairs, unions, power sets, an infinite set like , and images under definable functions. Everything in this lesson can be formalized in ZFC and, unless stated, without choice.
Functions
Domain, codomain, and image
Two functions are equal if they have the same domain, codomain, and values. Codomain is part of the function even if it seems a detail: from to and from to have the same values, but only the second is surjective. Programming types behave similarly: a Python function returning a nonnegative int and another annotated -> int doing the same compute alike but promise different things to callers.
Injective, surjective, bijective
Their negations, derived from quantifier laws, give counterexamples: is not injective if some have , and not surjective if some is no element’s image. Examples appearing later:
- , sigmoid, is a bijection from to : continuous and strictly increasing, with limits at of 0 and 1. Its inverse is logit, .
- Softmax, from to probability vectors with all positive components, is surjective but not injective: for every . Classifier logits are therefore determined only up to a constant.
- A tokenizer satisfying
decode(encode(s)) == sfor every string has injectiveencode: different texts never receive the same token list. The inverse theorem below guarantees this. - A cryptographic hash from arbitrary strings to 256 bits cannot be injective: infinitely many strings and only digests exist. It is required to make finding two inputs with the same image computationally difficult.
Composition
If and , composition is : on the right acts first. It is associative, , because both map to , and identity is neutral on both sides.
Proof
- If , injectivity of gives , and of gives . Conversely, given some has and some has , so .
- If , applying gives , and injectivity of gives .
- Given , some has , so satisfies .
The converses of 2 and 3 involving the other function are false; keep a counterexample handy. With , , , , and , composition is bijective, but is not surjective and not injective. Lost information is in : does not fill it and collapses it; sees neither.
Left and right inverses
Proof
- If , which is injective, the previous theorem makes injective. Conversely if is injective, each has a unique preimage . Fix (using ) and set if , otherwise . Then for all .
- If , which is surjective, the previous theorem makes surjective. Conversely if is surjective, every set is nonempty, and define by choosing one element from each. Then .
- If and , then . Parts 1 and 2 give equivalence, and this calculation proves uniqueness: every left inverse equals every right inverse.
The constructions have an important asymmetry. The left inverse is given by a formula. The right inverse chooses a preimage for each : if is infinite and there is no selection rule, the axiom of choice is needed, and “every surjection has a right inverse” is equivalent to that axiom. The interactive’s finite sets pose no problem, and it counts possible choices.
For finite sets the count is exact. If and , there are functions ; injective ones number , since each element of chooses an unused image, and the product is 0 if . This is the pigeonhole principle: with more pigeons than holes, two share one. If also , a function between finite sets of equal size is injective iff surjective, because its image has elements exactly when no collisions occur. This equivalence, often used automatically in linear algebra and combinatorics, is false for infinite sets: is injective from to and not surjective since nothing maps to 0. This is the first sign infinity behaves differently.
Image and preimage
Preimage exists for any function, invertible or not: is a set, not application of a function . For on , , , and . When is bijective, the preimage of under equals the image of under its inverse function, so notation causes no issue. Sets are fibers of ; distinct fibers are disjoint and their union is , so nonempty fibers partition the domain. A classifier’s fibers are decision regions.
Proof
Every preimage identity is a chain of equivalences. For union,
Intersection and complement are analogous with and ; complete them in the exercises. For image of a union, iff some in some has , iff some has : existential quantifiers commute. For intersection, “there exists in every ” implies “for each some is in ,” but the converse fails because can depend on : with , , and , whereas . Characterization by injectivity is the first guided exercise.
∎The two theorem columns have a simple interpretation: preimage asks something about for each domain point , and any logical connective passes inside unchanged. Image hides an existential quantifier, “some has ,” which commutes with and , but not , , or .
Step 1 of 4. For inclusion, let . What do you know?
Step 1 of 3. is equivalent to...
Cardinality
Equinumerosity
For finite sets “having the same number of elements” means pairing them one to one; that idea, not counting, generalizes.
Equinumerosity is reflexive (identity), symmetric (a bijection’s inverse is a bijection), and transitive (composition of bijections): an equivalence relation. For finite sets it coincides with equal element counts. For infinite sets it immediately contradicts intuition about parts and wholes:
- and the evens. is a bijection from to . An infinite set can be equinumerous with a proper subset; in fact a set is infinite iff this happens (with choice). Galileo observed it for perfect squares in 1638 and took it as evidence that “greater,” “less,” and “equal” do not apply to infinite quantities. Cantor defined “same size” by one-to-one correspondence; Dedekind (1888) turned the paradox into a definition of infinite set.
- and . Mapping for and for is a bijection from to : nonnegatives go to evens, negatives to odds.
- and . Sigmoid is a bijection from to . A bounded interval has as many points as the entire line.
- and . Adding two points changes nothing. The function mapping , , for , and fixing other points is a bijection from to : it shifts sequence two places to make room, as in Hilbert’s hotel.
For the last two, finding a bijection needs ingenuity; others are harder. The next theorem avoids this: two injections, one each way, usually easy, suffice.
Proof
Sketch. Assume and disjoint (otherwise replace them with disjoint copies). For each element trace its ancestor chain backward: if is in ‘s image, its parent is the unique with ; if that is in ‘s image, its parent is the unique with , and so on. Injectivity ensures at most one parent per element. Each backward chain either stops at a parentless element of , stops at one of , or never stops. This partitions into , , and according to chain origin, and likewise .
maps bijectively to : applying adds a link without changing origin, and every element of has a parent in because its chain does not stop there. Likewise maps bijectively to , and maps bijectively to . Define if and if , where is the existing parent of . The three pieces biject classes partitioning and , so is bijective. The construction is explicit and uses no choice.
∎The theorem makes immediate: inclusion is injective and maps injectively into . A deeper use needed later is :
- , , is injective: its ternary digits are 2 at positions in and 0 elsewhere, and a ternary expansion using only zeros and twos is unique.
- mapping to positions of ones in its binary expansion not ending in infinitely many ones is injective because that expansion exists uniquely.
With sigmoid, . The cardinality of is the continuum, , and we have shown .
Countability
The stated equivalence needs a lemma: every infinite subset is equinumerous with , because listing elements in increasing order gives bijection . If injects into , it is equinumerous with its image, finite or infinite and then equinumerous with . For nonempty , countability is also equivalent to a surjection , an enumeration in which every element appears at least once; no choice is needed: given a surjection, is an injection. Enumeration with repetition suffices to prove countability and is what we use.
The natural-number plane: Cantor pairing
The first surprise is is no larger than . Place pairs on an infinite grid. Traversing rows fails because the first never ends. Diagonals work: diagonal has cells, all diagonals are finite, and every cell lies on one. Diagonals before have cells total, the th triangular number. Numbering each diagonal bottom up gives cell the number
Proof
For each , values on diagonal are , exactly integers in , because . These intervals are disjoint and cover , so each lies in exactly one and has exactly one preimage there: is bijective. The inverse formula finds , the largest with ; the derivation follows.
∎The derivation’s last step is not technical trivia. If is computed in floating point with 53 mantissa bits, ceases to be exactly representable above , and near a perfect square rounding may cross an integer. The interactive gives an example: for , the naive version returns , a pair with a negative coordinate.
Unions, rationals, strings, and programs
Pairing makes almost everything built from finite pieces countable.
Proof
- If and are injections, is injective.
- Let be countable and nonempty (empty sets contribute nothing), and choose a surjection for each . Then , with , surjects from to . Choosing infinitely many enumerations at once uses a weak form of choice (countable choice); in this lesson’s concrete cases enumerations have formulas, so it is unnecessary.
- follows from the previous bijection. is the image of under , a surjection from a countable set.
- , and every is countable by point 1. A Python program is a finite byte string, so programs are a subset of for .
- bijects finite subsets of and : binary notation.
Binary strings have an elegant explicit bijection, shortlex order: length first, then lexicographic order at equal length, String number is obtained by writing in binary and removing the leading 1. Shortlex similarly enumerates strings over any finite alphabet of symbols (with bijective base- numeration); in the lab you will program it to assign print('hola') its natural number.
We now know algebraic numbers are countable (roots of integer-coefficient polynomials: countably many polynomials, each with finitely many roots) and so are computable reals, those for which a program given returns a rational within of : there are at most as many as programs. Every constant you have calculated, , , , Euler’s constant, is computable. Are all reals computable, or is countable?
The diagonal argument
Proof
Let be any sequence of elements of . Define sequence by
For each , , so : differs from the th sequence at position . Thus does not appear in the list, and no sequence of elements of enumerates them all. No surjection exists.
∎This construction is Cantor’s diagonal argument. Its strength is quantifier order: it does not say one particular list is incomplete, but that for every list a missing sequence exists, and it gives a way to construct one from that list. Any attempt to repair the list by adding missing creates a new list with its own diagonal.
Proof
We already know from , but the direct decimal argument is instructive. Let list numbers in , each with decimal expansion . Define with if and if . The expansion of contains neither zeros nor nines, hence is the unique decimal expansion of , and differs from at digit . Thus for every .
∎The 0-and-9 precaution is not pedantry: , so a diagonal merely changing digits could build another expansion of the same number. Choosing 4 and 5 avoids this. The argument proves much: computable reals are countable, so almost all reals are not computable, meaning their complement is countable and is not. Some can be precisely defined, such as the real whose binary digit is 1 iff the th program halts, but none can have arbitrarily many digits computed by a program: that would make it computable.
Cantor’s theorem
The argument does not depend on bit-sequence rows. Reading each sequence as the subset of where it is 1, the inverted diagonal is set , and the construction works over any set.
Proof
injects , so . It remains to show no bijection exists, for which it suffices that no is surjective. Given , consider the diagonal set
If for some , then , a contradiction. Thus is not in ‘s image.
∎This is Russell’s paradox turned into a theorem: gave contradiction there; the same trick applied inside a set shows a particular object cannot exist here. Consequences are far-reaching. Chain never ends: infinitely many sizes of infinity exist and none is greatest. The set of all sets cannot exist because it would contain as a subset and thus .
Step 1 of 3. Which subset do you propose?
Functions no program computes
Join both halves. Programs are countable because they are finite strings. Functions form , uncountable. Each program computes at most one function, so the vast majority of functions are computed by no program. Equivalently, a subset of is a function , so most decision problems on natural numbers (or programs numbered as above) are undecidable.
The cardinality argument proves existence without identifying one. To obtain a concrete one, diagonalize over the programs themselves. Number all programs , and suppose a program decides, given and , whether halts on input . Then the program
could be written using , would always terminate, and would be one of the listed programs, say . But then , a contradiction. Thus does not exist: the halting problem is undecidable, proven in detail in the computability lesson. The pattern matches the figure: rows are programs, with a diagonal and inversion. The only addition is that making the construction a program requires computing the diagonal, exactly what cannot be done.
Implementation: executable bijections and diagonals
All this fits in a few Python functions with exact integers. Start with the identity theorem: to decide a set identity, evaluate it in the “free model,” where each set is the set of Venn regions it contains. If it fails, differing regions are one-element counterexamples.
from itertools import product
def regiones(n):
"""Las 2^n regiones del diagrama de Venn de n conjuntos: cada una es un vector de pertenencias."""
return list(product((0, 1), repeat=n))
def modelo_libre(n):
"""Los conjuntos A_1..A_n, cada uno como el conjunto de las regiones que lo contienen, y el universo."""
R = regiones(n)
return [frozenset(r for r in R if r[i]) for i in range(n)], frozenset(R)
def identidad(lhs, rhs, n=3):
"""¿lhs = rhs para TODOS los conjuntos? Por el teorema, basta mirar el modelo de las regiones."""
S, U = modelo_libre(n)
a, b = lhs(*S, U), rhs(*S, U)
return a == b, sorted(a ^ b) # regiones donde difieren: cada una es un contraejemplo
casos = { # | unión, & intersección, - diferencia, ^ diferencia simétrica, U - X complemento
"(A ∪ B) ∖ (A ∩ C) = (A ∖ C) ∪ (B ∖ A)": (lambda A, B, C, U: (A | B) - (A & C), lambda A, B, C, U: (A - C) | (B - A)),
"(A ∪ B)ᶜ = Aᶜ ∩ Bᶜ": (lambda A, B, C, U: U - (A | B), lambda A, B, C, U: (U - A) & (U - B)),
"A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C)": (lambda A, B, C, U: A & (B | C), lambda A, B, C, U: (A & B) | (A & C)),
"(A △ B) △ C = A △ (B △ C)": (lambda A, B, C, U: (A ^ B) ^ C, lambda A, B, C, U: A ^ (B ^ C)),
"A ∖ (B ∖ C) = (A ∖ B) ∖ C": (lambda A, B, C, U: A - (B - C), lambda A, B, C, U: (A - B) - C),
"(A ∪ B) ∖ B = A": (lambda A, B, C, U: (A | B) - B, lambda A, B, C, U: A),
}
for nombre, (l, r) in casos.items():
ok, dif = identidad(l, r)
print(f"{nombre:40s} {'vale' if ok else 'falla en las regiones ' + str(dif)}")Regions read as : difference associativity fails at and , points of . The theorem says examining this model loses nothing. Check conversely with 2000 triples of random subsets of a 12-element universe:
import random
random.seed(0)
U12 = frozenset(range(12))
def al_azar():
return frozenset(x for x in U12 if random.random() < 0.5)
ternas = [(al_azar(), al_azar(), al_azar()) for _ in range(2000)]
for nombre, (l, r) in casos.items():
fallos = sum(l(A, B, C, U12) != r(A, B, C, U12) for A, B, C in ternas)
print(f"{nombre:40s} falla en {fallos:4d} de 2000 ternas al azar")Valid identities never fail, and false ones almost always fail: one of 12 elements merely needs to land in either bad region. Now finite-set functions. Represent by its image tuple, count injections and surjections by brute force, and compare with formulas: for injections and inclusion–exclusion for surjections, subtracting functions missing an element.
from math import comb, perm
def funciones(m, n):
"""Todas las funciones de {0..m-1} en {0..n-1}, como tuplas de imágenes."""
return list(product(range(n), repeat=m))
def es_inyectiva(f):
return len(set(f)) == len(f)
def es_sobreyectiva(f, n):
return set(f) == set(range(n))
def sobreyecciones(m, n):
return sum((-1) ** k * comb(n, k) * (n - k) ** m for k in range(n + 1))
print(" m n funciones inyectivas sobreyectivas")
for m, n in [(3, 3), (3, 5), (4, 3), (5, 5), (6, 3)]:
F = funciones(m, n)
iny = sum(map(es_inyectiva, F))
sob = sum(es_sobreyectiva(f, n) for f in F)
assert iny == perm(n, m) and sob == sobreyecciones(m, n) # math.perm(n, m) = 0 si m > n
print(f"{m:2d} {n:2d} {len(F):10d} {iny:11d} {sob:14d}")
def compon(g, f):
return tuple(g[y] for y in f)
def contraejemplos(hip, concl, tam=3):
"""Parejas (f, g), con todos los tamaños hasta tam, que cumplen la hipótesis y no la conclusión."""
total = malos = 0
for m, n, p in product(range(1, tam + 1), repeat=3):
for f in funciones(m, n):
for g in funciones(n, p):
total += 1
malos += hip(f, g, n, p) and not concl(f, g, n, p)
return malos, total
afirmaciones = {
"g∘f inyectiva ⇒ f inyectiva": (lambda f, g, n, p: es_inyectiva(compon(g, f)), lambda f, g, n, p: es_inyectiva(f)),
"g∘f inyectiva ⇒ g inyectiva": (lambda f, g, n, p: es_inyectiva(compon(g, f)), lambda f, g, n, p: es_inyectiva(g)),
"g∘f sobreyectiva ⇒ g sobreyectiva": (lambda f, g, n, p: es_sobreyectiva(compon(g, f), p), lambda f, g, n, p: es_sobreyectiva(g, p)),
"g∘f sobreyectiva ⇒ f sobreyectiva": (lambda f, g, n, p: es_sobreyectiva(compon(g, f), p), lambda f, g, n, p: es_sobreyectiva(f, n)),
}
for nombre, (h, c) in afirmaciones.items():
malos, total = contraejemplos(h, c)
print(f"{nombre:35s} contraejemplos: {malos:5d} de {total}")The two theorem claims have no counterexample among all pairs on sets up to three elements; the other two have 198 and 135 of 1618 pairs. Move to infinity. Cantor pairing and its inverse in exact integer arithmetic with math.isqrt, which computes for arbitrarily large integers without floating point:
import math
def pair(x, y):
return (x + y) * (x + y + 1) // 2 + y
def unpair(n):
w = (math.isqrt(8 * n + 1) - 1) // 2 # mayor w con T_w <= n, sin coma flotante
y = n - w * (w + 1) // 2
return w - y, y
N = 200_000
assert all(pair(*unpair(n)) == n for n in range(N)) # π ∘ π⁻¹ = id en [0, N)
celdas = [(x, w - x) for w in range(400) for x in range(w + 1)] # diagonales x + y < 400
assert sorted(pair(x, y) for x, y in celdas) == list(range(len(celdas))) # ocupan exactamente [0, T_400)
assert all(unpair(pair(x, y)) == (x, y) for x, y in celdas)
print("π(3, 4) =", pair(3, 4), " π⁻¹(100) =", unpair(100), " π⁻¹(10⁶) =", unpair(10**6))
def unpair_float(n):
w = int((math.sqrt(8 * n + 1) - 1) // 2) # la versión ingenua
y = n - w * (w + 1) // 2
return w - y, y
n = pair(0, 2**27 - 1)
print(f"n = {n}: exacta {unpair(n)}, coma flotante {unpair_float(n)}")
print("enteros enormes sin problema:", unpair(pair(10**40, 7)) == (10**40, 7))Exhaustive checking is the honest way to test a bijection in code: it proves nothing outside the range, but any one-step error appears quickly. Floating-point failure, conversely, never appears in any small range: the first of form where it fails is exactly the cell’s, with . Reason about precision rather than trusting tests.
Finite strings. The shortlex bijection from to binary strings and its byte generalization, bijective base-256 numeration, gives every program its number:
from itertools import count, islice
def cadena(n):
"""n-ésima cadena binaria en orden shortlex: n + 1 en binario sin el 1 inicial."""
return bin(n + 1)[3:]
def indice(s):
return int("1" + s, 2) - 1
print([cadena(n) for n in range(15)])
assert all(indice(cadena(n)) == n for n in range(100_000))
def shortlex():
"""Todas las cadenas binarias: por longitud y, dentro de cada longitud, en orden lexicográfico."""
for L in count(0):
for t in product("01", repeat=L):
yield "".join(t)
assert list(islice(shortlex(), 2**12 - 1)) == [cadena(n) for n in range(2**12 - 1)]
def indice_bytes(b: bytes) -> int:
"""Numeración biyectiva en base 256: la cadena vacía es 0 y el orden es shortlex."""
k = 0
for byte in b:
k = 256 * k + byte + 1
return k
def bytes_de(k: int) -> bytes:
out = bytearray()
while k > 0:
k, r = divmod(k - 1, 256)
out.append(r)
return bytes(reversed(out))
assert all(indice_bytes(bytes_de(k)) == k for k in range(70_000))
programa = "print('hola')"
k = indice_bytes(programa.encode("utf-8"))
print(f"{programa!r} es el programa número {k} ({len(str(k))} cifras)")
print("y el número k vuelve a ser el programa:", bytes_de(k).decode("utf-8"))Every Python program occupies a place in this list alongside byte strings that are not valid programs. Finally diagonalization. Function diagonal receives any enumerator, a function returning the th sequence as a Python function given , and returns a sequence not in the list. Test three enumerators: all sequences with finitely many ones, all periodic ones, and a pseudorandom list.
import matplotlib.pyplot as plt
import numpy as np
from itertools import combinations
def diagonal(enum):
"""enum(n) es la n-ésima sucesión (una función i -> 0 o 1). La diagonal difiere de todas."""
return lambda i: 1 - enum(i)(i)
def primeros(s, k=36):
return "".join(str(s(i)) for i in range(k))
finitos = lambda n: (lambda i: (n >> i) & 1) # n en binario, al revés
periodicas = lambda n: (lambda i, p=cadena(n + 1): int(p[i % len(p)])) # el patrón n-ésimo, repetido
aleatorias = lambda n: (lambda i: random.Random(1009 * n + i).getrandbits(1))
for nombre, enum in [("finitos unos", finitos), ("periódicas", periodicas), ("aleatorias", aleatorias)]:
d = diagonal(enum)
assert all(d(k) != enum(k)(k) for k in range(3000))
print(f"{nombre:13s} d = {primeros(d)}...")
# el teorema de Cantor, exhaustivo en un conjunto pequeño: todas las f: A -> P(A) con |A| = 3
A = range(3)
partes = [frozenset(c) for r in range(4) for c in combinations(A, r)]
for imagenes in product(partes, repeat=3): # 8³ = 512 funciones
D = frozenset(a for a in A if a not in imagenes[a])
assert D not in imagenes
print(f"{len(partes) ** 3} funciones A -> P(A): ninguna tiene el conjunto diagonal en su imagen")
K = 16
T = np.array([[periodicas(n)(i) for i in range(K)] for n in range(K)])
fig, ax = plt.subplots(figsize=(6.2, 4.4))
ax.imshow(np.vstack([T, np.full((1, K), np.nan), [[diagonal(periodicas)(i) for i in range(K)]]]), cmap="Blues", vmin=-0.4, vmax=1.4)
ax.plot(range(K), range(K), "s", ms=11, mfc="none", mec="C3", mew=1.6)
ax.set_yticks(list(range(K)) + [K + 1], [f"s{n}" for n in range(K)] + ["d"])
ax.set_xticks(range(K)); ax.set_title("Sucesiones periódicas y su diagonal invertida")
plt.tight_layout()
plt.show()All three diagonals differ from every row, as the proof guarantees. The first is , the infinite-ones sequence absent from the finite-ones list. The second is not periodic and cannot be, because the list includes every periodic pattern. The final output line checks Cantor’s theorem over all functions in a small case.
The professional version
Python set data structures implement this lesson’s operations, with a trap: set is mutable and cannot be placed inside another set; for sets of sets such as use frozenset. Operators distinguish from as on paper: x in S is membership, S <= T inclusion.
A = frozenset({1, 2})
P = {frozenset(c) for r in range(3) for c in combinations(A, r)} # P(A), un conjunto de frozensets
print(sorted(map(sorted, P)))
print("{1} ∈ P(A):", frozenset({1}) in P, " {1} ⊆ A:", {1} <= A, " {1} ⊆ P(A):", frozenset({1}) <= P)
print("∅ ∈ P(A) y ∅ ⊆ P(A):", frozenset() in P, frozenset() <= P)
try:
{{1, 2}}
except TypeError as e:
print("un set dentro de un set:", e)frozenset({1}) <= P asks whether element 1 is in P, and it is not: P’s elements are sets. To decide identities symbolically, SymPy translates to logic, exactly as the identity theorem: the identity holds iff formula “both sides differ” is unsatisfiable.
from sympy import symbols
from sympy.logic.boolalg import And, Or, Not, Xor
from sympy.logic.inference import satisfiable
a, b, c = symbols("a b c") # a significa «x ∈ A»
lhs = And(Or(a, b), Not(And(a, c))) # x ∈ (A ∪ B) ∖ (A ∩ C)
rhs = Or(And(a, Not(c)), And(b, Not(a))) # x ∈ (A ∖ C) ∪ (B ∖ A)
print("¿difieren en alguna región?", satisfiable(Xor(lhs, rhs)))
print("A ∖ (B ∖ C) frente a (A ∖ B) ∖ C:", satisfiable(Xor(And(a, Not(And(b, Not(c)))), And(a, Not(b), Not(c)))))satisfiable returns False when no valuation distinguishes the sides (the identity holds), otherwise a specific counterexample region: here and true, false, region already found. For three or four sets this matches the truth table, but with dozens the table has too many rows and a SAT solver still works: the idea of satisfiability lessons. SymPy also computes interval images and preimages:
from sympy import Interval, Lambda, imageset, solveset, S
x = symbols("x", real=True)
f = Lambda(x, x**2)
A1, A2 = Interval(-2, -1), Interval(1, 2)
print("f(A1 ∩ A2) =", imageset(f, A1.intersect(A2)), " f(A1) ∩ f(A2) =", imageset(f, A1).intersect(imageset(f, A2)))
print("f⁻¹([0, 4]) =", solveset(x**2 <= 4, x, S.Reals), " f⁻¹({−1}) =", solveset(x**2 + 1, x, S.Reals))The two lines show image/preimage asymmetry concretely: , whereas .
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
math.sqrt. It passes small tests but fails on large numbers. Correct unpair(n) to use only integer arithmetic (math.isqrt, //) and return pair (x, y) with for any natural , however large.import math
def pair(x, y):
return (x + y) * (x + y + 1) // 2 + y
def unpair(n):
w = int((math.sqrt(8 * n + 1) - 1) // 2)
y = n - w * (w + 1) // 2
return w - y, ySummary
- Sets. Boolean set operations are logical connectives applied to “ belongs.” An identity holds for all sets iff its formula is logical equivalence iff both sides contain the same Venn regions; any failure occurs with one element. Prove by double inclusion.
- Functions. Injectivity means a left inverse and surjectivity a right inverse (the latter chooses preimages). If is injective, so is ; if surjective, so is ; converses about the other function fail.
- Image and preimage. Preimage preserves unions, intersections, and complements of arbitrary families and exists for every function. Image preserves only unions. Measurability and random variables are therefore defined using preimages.
- Cardinality. if an injection exists; injections each way give a bijection (Cantor–Schröder–Bernstein). An infinite set can be equinumerous with a proper part.
- Countability. bijects , and its inverse uses
math.isqrt, notsqrt. Countable unions of countable sets, , , and programs are countable. - Diagonal. escapes any list: and are uncountable, and for every . Applied to programs, the same diagonal proves halting undecidable.