Prefix codes, Kraft's inequality and Huffman coding
Build symbol-by-symbol codes from prefix trees, derive the Kraft–McMillan inequality and the bounds H ≤ L* < H + 1, and prove Huffman optimality. Connect compression to learning by measuring the D(p‖q) extra ideal bits per symbol from coding with a mismatched model q.
After this lesson you can
- Construct prefix codes and use their trees to check instantaneous decodability.
- Prove Kraft’s inequality and state McMillan’s extension to uniquely decodable codes.
- Derive the ideal lengths ℓ = −log p with Lagrange multipliers and prove H ≤ L* < H + 1.
- Implement Huffman coding and use exchange arguments to prove optimality.
- Quantify the cost of designing a code for q when the source is p.
Before you start
Motivation: from Morse to zip
A source emits four symbols with probabilities . Its entropy is bits, and the source coding theorem promises that encoding long blocks lets us approach that figure arbitrarily closely. But a real compressor does not encode infinite blocks: it assigns each symbol a word of zeros and ones, concatenates the words and expects the receiver to separate them. What does that symbol-by-symbol code cost? Fixed-length words need 2 bits. Code gives bits. Using the lengths suggested by surprise, , gives . Three codes, three costs, all above . Is the best possible? Why can’t we go below ? How much is lost by not knowing well?
These old questions, which Samuel Morse faced when assigning “e” one dot and “q” four signals, are answered with mathematical precision in this lesson. Morse code also hides an instructive trap: one dot is “e”, two consecutive dots are “i”, so the signal sequence alone is ambiguous and the telegraph operator needs a pause between letters. Morse is actually a ternary code (dot, dash and silence). With a binary alphabet that pause does not exist, and word separation must be guaranteed by the code’s structure itself. This gives the lesson’s ideas:
- Prefix codes. A simple condition, that no word begins another, allows decoding on the fly and can be read as a tree.
- The Kraft–McMillan inequality. Which length lists are possible? This is a budget condition: each -bit word consumes and the total cannot exceed 1.
- The bounds . The best symbol-by-symbol code cannot beat entropy and exceeds it by at most one bit.
- Huffman. A ten-line greedy algorithm constructs the optimal code, with an exchange proof of optimality.
- The wrong model. If the code is designed for but data come from , the excess is exactly bits per symbol. This bridges compression and learning: the cross-entropy loss used to train language models is a code length.
This is not engineering folklore. The DEFLATE code in zip, gzip and PNG (repetition search, LZ77, followed by Huffman codes) and JPEG’s entropy stage rest on what follows. Unless otherwise stated, is base-2 logarithm, lengths are measured in bits and the code alphabet is binary ; the end of the Kraft section describes what changes for an alphabet of symbols.
Codes, words and instantaneous decoding
Let be a finite source-symbol alphabet (the source is a random variable with mass ) and the set of finite binary strings. A code is a map ; is the word for and its length. We always assume for every (an impossible symbol needs no word) and nonempty words. Code quality is measured by its mean length
To encode a sequence , concatenate the words, . For this to work, the receiver must be able to invert it. There are three levels of requirement, each stronger than the last:
- Nonsingular: implies . Enough to describe one symbol, but not a sequence: with , , , the string may be or .
- Uniquely decodable (UD): concatenation is injective, meaning distinct symbol sequences (of any length) produce distinct bit strings.
- Prefix (or instantaneous): no word is a prefix of another. This is the class we will almost always use.
Each class contains the next: prefix implies UD implies nonsingular, and inclusions are strict. The first follows from the decoding algorithm itself. To decode a prefix code, read bit by bit and, the moment the bits read match a word, emit its symbol and start again. There is never a need to look at further bits to see whether “that” could start another word: no word starts with this one. Hence instantaneous, with no delay or buffering.
A prefix code is a tree
Draw the full binary tree: each node has two outgoing edges, the left labeled and the right . A node at depth is identified by the -bit string from the root to it. A code is a set of nodes, one per symbol, and is prefix precisely when no chosen node is an ancestor of another (a word’s descendants are unusable because each has that word as prefix). A word’s length is its depth. The “twenty questions” of lesson 1 are this same tree read as an interrogation: each bit is a yes-or-no answer, and decoding ends at a leaf. For the rooted tree theory used here see rooted tree.
This picture turns a combinatorial problem (whether are the lengths of a prefix code) into a problem of space. There are finitely many nodes: choosing one at depth eliminates its whole subtree. But a node at depth does not “cost” the same as one at depth : half the tree (50%) hangs from each child of the root, a quarter from each grandchild, and generally a node at depth governs fraction of all tree leaves. That fraction is the word’s price. The figure shows the tree laid out in rows, with each node’s width proportional to its price.
What the figure suggests, and what is proved next, is that the sum is the only obstacle. Any length list whose prices sum to at most 1 has room for all words; once the sum exceeds 1, the last ones do not fit, however they are placed.
The Kraft–McMillan inequality
The proof has three parts: the condition is necessary for prefix codes, sufficient (by construction), and necessary even for UD codes.
Proof
Necessity for prefix codes. Let and consider the full binary tree of depth , with leaves. Word is a node at depth , below which lie exactly leaves of the full tree (the remaining bits may be arbitrary). If and , with , shared a leaf, that leaf would be a string beginning with both and , and the shorter would be a prefix of the other: contradiction. Hence the leaf sets are disjoint, and their union fits in the leaves:
Equality holds if and only if leaves descending from words cover the whole tree, i.e. no leaf remains free.
Sufficiency (construction). Suppose and order the lengths, . Define cumulative sums
and let be the string formed by the first binary digits of . This makes sense: is a multiple of and , so has a finite binary expansion of at most digits, all captured by ; and , so all those digits are to the right of the binary point. Viewed as an interval, corresponds to dyadic interval . If were a prefix of with , point would lie in , i.e. . But because cumulative sums increase with the index. Contradiction: no is a prefix of another.
McMillan: necessity for UD codes. Let be uniquely decodable, with lengths and . For ,
where counts -tuples whose concatenation has bits. Since is UD, distinct tuples give distinct strings, and there are only strings of bits: . Thus each summand is at most 1 and
Since is arbitrary, .
∎Three things to retain.
- McMillan closes the door to tricks. Since every UD code’s lengths satisfy Kraft, a prefix code exists with the same lengths (the construction above) and thus the same mean length. Giving up instantaneous decoding saves not a single bit on average: to find the best code, prefix codes suffice. This is why hardly anyone discusses UD non-prefix codes.
- Kraft only concerns lengths. It does not specify which words to use, and indeed there are many equivalent choices (swapping 0 and 1 at any internal node gives another prefix code with the same lengths). It does say which lengths are possible, and that is all an optimization problem needs: mean length depends only on lengths.
- For a code alphabet of symbols the proof is the same, counting leaves: the condition is . Exercises and figures keep .
An immediate consequence of the construction is an operational test: lengths sum to , so a prefix code exists and gives from the motivation. Lengths sum to and no code is possible, prefix or UD. This is exactly what happens to in the figure when it attempts to enter an already full tree.
Ideal lengths and the lower bound
We can now state the optimization problem: choose lengths to minimize subject to and being integers. The integer constraint makes the problem hard to handle by hand. A classic trick is to drop it first, solve the relaxed problem with , and see what remains.
The relaxed problem is convex: the objective is linear in and the constraint is convex (a sum of exponentials). Lagrange optimality conditions are therefore sufficient. With Lagrangian :
This is a neat result: surprise from the first lesson is the ideal length of the word for , and entropy is the ideal cost. Since integer lengths are a special case of real lengths, the relaxed minimum is already a lower bound for any code. But a direct, much more informative proof also tells us how much is lost when lengths are not ideal. This is the lesson’s central identity.
Proof
With we have , and
∎Both summands are nonnegative, each with an interpretation. by Gibbs’ inequality: it is the price of lengths (normalized, ) describing poorly. when Kraft holds: this is the wasted budget, bits that could have been saved because the tree has free leaves. It quantifies the previous figure.
By Kraft (or McMillan), , so ; by Gibbs, . Equality holds only if and , i.e. , and since is an integer, is a power of . With none of the probabilities is, so no code has . Check the motivation’s numbers: for lengths we have and with ; for we have , and excess splits into of divergence and of unused leaves. That second code wastes nearly all its excess in the unfilled tree.
The upper bound: Shannon coding
The lower bound does not say we can get close. This does: just round ideal lengths up.
Let . Since , we have and therefore
that is, Kraft holds and there is a prefix code with those lengths: the Shannon code (using the canonical construction from the preceding section). Its mean length is
The lower bound is the previous corollary (and holds for any UD code); the upper bound is the Shannon code. For blocks apply the same result to variable , whose entropy is since the are independent (lesson 1). This is the lossless variable-length version of the source coding theorem: the asymptotic version in lesson 4 said one can approach with vanishing error and long blocks, and this says the same with no error, real prefix codes, and explicit excess decreasing as .
Two often-forgotten nuances:
- The Shannon code is not optimal. With it gives (even worse than fixed length 2 bits) and with gives bits, although with 1 bit suffices. Rounding lengths separately does not consider the whole and leaves free leaves in the tree (the in the identity). An algorithm must jointly optimize integer lengths.
- The bound cannot be improved for symbol-by-symbol codes. With entropy tends to 0 as , but any code on two symbols needs at least one bit per symbol: . The excess approaches 1. This case dominates later when discussing Huffman’s limits.
The Huffman algorithm
In 1951 David Huffman was a doctoral student at MIT taking Robert Fano’s information theory course, where students chose between a final exam and a paper: find the minimum-mean-length binary code. Fano himself had proposed a top-down code (splitting the alphabet into two groups of similar probability, called Shannon–Fano coding) that is not always optimal. Huffman, unaware the problem was open, found the optimum by building the tree bottom up and published it in 1952 in a short paper: A Method for the Construction of Minimum-Redundancy Codes.
It takes merges. With a priority queue implemented as a binary heap, each operation costs and the whole algorithm . If probabilities are already sorted, two ordinary queues suffice (one for leaves and one for created nodes, which emerge in increasing order) at cost . Try the figure: choose an example and reproduce the construction, enter frequencies, or paste text.
With : merge and the queue becomes ; then , and finally . The weights of the three internal nodes sum to , exactly the mean length of the resulting code . This is no coincidence, and the identity explains what the figure shows.
The reason is counting: a leaf at depth has exactly internal ancestors (including the root), so its probability is added times in the total, and . This makes Huffman a cost procedure: each merge pays the weight of the created node, and merging the lightest is the greedy way to make each payment as small as possible.
Why it is optimal
A greedy algorithm need not succeed: removing the two lightest is a local decision, and the global optimum might require another. The proof uses two lemmas, one exchange and one reduction to a smaller problem. Order the symbols, , with .
Proof
Let be an optimal prefix code and its tree.
(a) More probable symbols have shorter words. If and , swapping words of and gives another prefix code, with mean length
contradicting optimality of . Thus implies .
(b) The tree of is full. If an internal node had only one child, it could be removed (raising its entire subtree one level), shortening all words below by one bit, all with positive probability: would strictly decrease. Contradiction. Thus every internal node has two children.
(c) Siblings at maximum depth. Let be a maximum-depth leaf. By (b) it has a sibling , and is a leaf: otherwise it would have descendants deeper than . Both are thus at maximum depth . We must put symbols and there. Let be the symbol of , and suppose . If , swapping words of and does not change because they have equal lengths. If , then : from , (a) would imply , absurd. Since is the minimum probability, , and the swap changes by . In either case the code stays optimal and, without loss of generality, is at . Let be the symbol of . The same reasoning, with in the role of ( is minimum among symbols other than ), lets us swap and without changing or moving . The resulting code is optimal and has and as siblings at maximum depth.
∎The identity is immediate: the two new words are one bit longer than the merged one and the rest is unchanged, so mean length increases by . Conversely, if two leaves are siblings, replacing them with their parent gives a valid prefix code on .
Proof
By induction on (structural induction on the tree construction; see structural induction). For the only possible code is , which Huffman gives. Assume the result for symbols and let have symbols. Step 2 merges the two lightest, and , and the rest of the algorithm is exactly Huffman on . By hypothesis, that remainder produces an optimal code for , and Huffman code for is its expansion: by the reduction lemma.
Now let be an optimal code for in which and are siblings (it exists by the exchange lemma). By the converse of the reduction lemma, it expands a for , so
Since also by definition of optimality, .
∎This is an exchange argument typical of greedy algorithms (exchange argument): yielding on the local decision is shown never to improve the result. The proof does not say the optimum is unique: when weights tie, several Huffman codes exist, all with the same but different length distributions. In practice it is useful to break ties so newly created nodes emerge after equal-weight leaves: among optima this gives minimum length variance, requiring least buffering on a constant-rate channel. The figure (and implementation below) does this.
The price of the wrong model
Huffman coding is optimal for . In practice is unknown: it is estimated, assumed or inherited from another dataset. Imagine designing a code for distribution , with lengths (ideal, unrounded for now), and data actually come from . Mean length is
the cross entropy (lesson 6 studies it deeply). By the redundancy identity, with and :
Kullback–Leibler divergence is no longer abstract: it is the extra cost in bits of describing data with the code (the “excess surprise” interpretation from lesson 2, now with an operational proof). With and an engineer assuming uniform : , , . If reverses , , the excess is bits, more. And if assigns mass to the most frequent symbol and splits the rest equally, , we get : you pay almost 7 bits each time a symbol that occurs half the time appears.
Three readings of the same quantity come together here and accompany the rest of the module:
- Compression. is what you lose by using a code fitted to . If forbids a symbol that occurs (infinite length), you pay : the code has no word.
- Learning. If is a language model and the real text, mean cross-entropy loss measured in bits is , the mean length of the code a model-based compressor would build. Training shortens that code. The minimum possible, , is language’s irreducible noise (lesson 6).
- Statistics. The same number is mean evidence per observation for against (lesson 2), so a model that makes few errors is one that costs little to describe.
Huffman’s limits and the value of blocks
Huffman is optimal among symbol-by-symbol codes with known distribution. Outside those assumptions it makes no promise, and both assumptions have costs.
Symbol by symbol. Each symbol uses an integer number of bits, so it can never cost less than one. For a binary source the code is for any and always, however tiny entropy is. With , : the code uses times the necessary bits. In general (Gallager, 1978), Huffman redundancy is at most , where is the most frequent symbol’s probability: it is worse the more biased the source, precisely when compression seemed most promising.
Blocks. The remedy is the block bound above: applying Huffman to the alphabet of -symbol blocks lowers the excess per symbol to at most . But alphabet size grows as : a binary source with already needs a table of words, and with 256 symbols (bytes) and , over four billion. The figure lets you explore the tradeoff.
Three observations are clear in the figure. First: with , length per symbol is , , , for and for , against . Improvement is enormous at first and slow afterward. Second: excess does not decrease monotonically. Bound guarantees only a ceiling; what happens inside depends on how block masses align with powers of : with excess is at , falls to at and rises to at . With length falls to at (excess ), then rises at () and to (); eventually it tends to because excess stays below , but not monotonically. Third: convergence is slow for a highly biased source. With and (a table of words), bits per symbol remain versus , more; exceeding is needed to get below .
There is also a cost hidden by length theory: the receiver must know the code. If the table is sent, its header counts and in a small file may exceed the saving; if adaptively estimated, the tree must stay updated. Arithmetic coding (lesson 7) solves both at once: it treats the whole sequence as one symbol, without a block table or per-symbol rounding, with total excess bits over the whole sequence (for model , per symbol plus a constant). Thus modern compressors with a next-symbol prediction model, whether a low-order context or transformer, use arithmetic coding rather than Huffman. Huffman remains standard where speed and simplicity dominate: it is the last stage of DEFLATE, JPEG and many other formats.
Implementation from scratch
First, Huffman with heapq (a binary heap, like the one in the algorithms lesson). Queue entries are (peso, orden, árbol) tuples: the second element breaks ties in creation order (leaves created earlier emerge before equal-weight internal nodes) and prevents Python comparing two trees. The code checks the lesson’s proofs: Kraft equality, the redundancy identity, bit-by-bit decoding and agreement between measurements on a sample of symbols and theory.
import heapq, math
import numpy as np
def huffman(pesos):
"""pesos: dict símbolo -> peso. Devuelve dict símbolo -> palabra (cadena de ceros y unos)."""
if len(pesos) == 1:
return {s: "0" for s in pesos}
# entradas (peso, orden de creación, árbol); un árbol es un símbolo (hoja) o una pareja (izq, der)
cola = [(w, i, s) for i, (s, w) in enumerate(pesos.items())]
heapq.heapify(cola)
creados = len(cola)
while len(cola) > 1:
w1, _, a = heapq.heappop(cola) # el más ligero va a la izquierda (bit 0)
w2, _, b = heapq.heappop(cola)
heapq.heappush(cola, (w1 + w2, creados, (a, b)))
creados += 1
codigo = {}
def recorre(arbol, prefijo):
if isinstance(arbol, tuple):
recorre(arbol[0], prefijo + "0")
recorre(arbol[1], prefijo + "1")
else:
codigo[arbol] = prefijo
recorre(cola[0][2], "")
return codigo
def longitud_media(p, codigo):
return sum(p[s] * len(codigo[s]) for s in p)
def entropia(p):
return -sum(x * math.log2(x) for x in p.values() if x > 0)
p = {"a": 0.4, "b": 0.3, "c": 0.2, "d": 0.1}
codigo = huffman(p)
L, H = longitud_media(p, codigo), entropia(p)
print("código de Huffman:", dict(sorted(codigo.items())))
print(f"L = {L:.4f} H = {H:.4f} L - H = {L - H:.4f}")
# Kraft con igualdad (el árbol de Huffman siempre es lleno)
S = sum(2.0 ** -len(w) for w in codigo.values())
print("suma de Kraft =", S)
# identidad de la redundancia: L - H = D(p || r) + log2(1/S), con r = 2^-l / S
r = {s: 2.0 ** -len(codigo[s]) / S for s in p}
D = sum(p[s] * math.log2(p[s] / r[s]) for s in p)
print(f"D(p||r) + log2(1/S) = {D + math.log2(1 / S):.4f}")
# código de Shannon: l = ceil(-log2 p)
ls = {s: math.ceil(-math.log2(p[s])) for s in p}
Ss = sum(2.0 ** -l for l in ls.values())
Ls = sum(p[s] * ls[s] for s in p)
Dr = sum(p[s] * math.log2(p[s] / (2.0 ** -ls[s] / Ss)) for s in p)
print(f"Shannon: longitudes {ls}, suma de Kraft {Ss:.4f}, L = {Ls:.4f} (exceso {Ls - H:.4f} = {Dr:.4f} + {math.log2(1 / Ss):.4f})")
# codificar y decodificar bit a bit
def codifica(texto, codigo):
return "".join(codigo[s] for s in texto)
def decodifica(bits, codigo):
inverso = {w: s for s, w in codigo.items()}
salida, actual = [], ""
for b in bits:
actual += b
if actual in inverso: # coincide con una palabra: emitir y empezar de nuevo (instantáneo)
salida.append(inverso[actual])
actual = ""
assert actual == "", "bits sobrantes: el flujo estaba truncado"
return "".join(salida)
rng = np.random.default_rng(0)
muestra = "".join(rng.choice(list(p), size=10_000, p=list(p.values())))
bits = codifica(muestra, codigo)
assert decodifica(bits, codigo) == muestra
print(f"10 000 símbolos -> {len(bits)} bits = {len(bits) / 10_000:.4f} bits por símbolo (teoría {L})")The code reproduces the motivation’s figures. The Kraft sum is exactly 1, the redundancy identity matches excess , and the Shannon code with wastes almost all excess on unused leaves. Decoding recovers the sample losslessly without any length information: only the table is needed. For the sample of symbols, measured length is bits per symbol, versus theoretical .
The second piece is what a real compressor needs: (i) do not transmit the tree, only lengths, and reconstruct words with the same rule as the Kraft proof (the canonical code: sort symbols by length and, within equal lengths, by symbol, and assign each the next binary number); (ii) pack bits into bytes, with padding; and (iii) measure total size, including the header. This is exactly what DEFLATE and JPEG do: the header describes lengths, not words.
import contextlib, difflib, inspect, io, math
from collections import Counter
def codigo_canonico(longitudes):
"""Palabras canónicas a partir de las longitudes (la construcción de la demostración de Kraft)."""
orden = sorted(longitudes, key=lambda s: (longitudes[s], s))
codigo, c, anterior = {}, 0, 0
for s in orden:
l = longitudes[s]
c <<= (l - anterior) # pasa el acumulado a la escala de l bits
assert c < (1 << l), "las longitudes violan Kraft"
codigo[s] = format(c, f"0{l}b")
c += 1 # el siguiente nodo libre a la derecha
anterior = l
return codigo
def comprime(datos):
"""datos: bytes. Devuelve (fichero, bits del cuerpo). Formato: n, [símbolo, longitud] * n, relleno, cuerpo."""
frec = Counter(datos)
longitudes = {s: len(w) for s, w in huffman(dict(frec)).items()}
codigo = codigo_canonico(longitudes)
bits = "".join(codigo[b] for b in datos)
relleno = (-len(bits)) % 8
cuerpo = bytes(int((bits + "0" * relleno)[i:i + 8], 2) for i in range(0, len(bits) + relleno, 8))
cabecera = bytes([len(longitudes) - 1]) # 1 byte: número de símbolos - 1 (hasta 256)
for s in sorted(longitudes, key=lambda s: (longitudes[s], s)):
cabecera += bytes([s, longitudes[s]]) # 2 bytes por símbolo
return cabecera + bytes([relleno]) + cuerpo, len(bits)
def descomprime(fichero, n):
k = fichero[0] + 1
longitudes = {fichero[1 + 2 * i]: fichero[2 + 2 * i] for i in range(k)}
pos = 1 + 2 * k
relleno, cuerpo = fichero[pos], fichero[pos + 1:]
bits = "".join(format(b, "08b") for b in cuerpo)
bits = bits[:len(bits) - relleno] if relleno else bits
inverso = {w: s for s, w in codigo_canonico(longitudes).items()}
salida, actual = bytearray(), ""
for b in bits:
actual += b
if actual in inverso:
salida.append(inverso[actual]); actual = ""
return bytes(salida)
def entropia_bytes(datos):
n = len(datos)
return -sum(c / n * math.log2(c / n) for c in Counter(datos).values())
with contextlib.redirect_stdout(io.StringIO()): # `import this` imprime el Zen de Python: lo silenciamos
import this
zen = "".join(this.d.get(c, c) for c in this.s).encode()
largo = inspect.getsource(difflib).encode() # unos 84 kB de texto real, determinista
for nombre, datos in [("el Zen de Python", zen), ("el código de difflib", largo)]:
fichero, nbits = comprime(datos)
assert descomprime(fichero, len(datos)) == datos
H = entropia_bytes(datos)
print(f"{nombre}: {len(datos)} bytes")
print(f" entropía de orden 0: {H:.3f} bits/símbolo -> cota {H * len(datos) / 8:.0f} bytes")
print(f" Huffman: cuerpo {nbits / len(datos):.3f} bits/símbolo = {math.ceil(nbits / 8)} bytes; con cabecera, {len(fichero)} bytes ({8 * len(fichero) / len(datos):.3f} bits/símbolo)")Two effects appear together. In the long text (84 kB), the body costs bits per symbol versus order-0 entropy : bits away, far below bound , which is pessimistic when no symbol dominates. The header is bytes of , . In the Zen of Python ( bytes), the body is bytes and header : of the file, so the total ( bits per symbol) is almost one bit above order-0 entropy (). This is the table-transmission cost warned about above. Without the header the decompressor does not know which code was used, so real formats spend effort describing the tree in few bytes (DEFLATE encodes lengths themselves with another Huffman code).
Finally, the block experiment, measured rather than just calculated: Huffman on the block alphabet of a biased binary source, and a real sequence of symbols encoded with .
import math
from itertools import product
import numpy as np
def h2(p):
return -p * math.log2(p) - (1 - p) * math.log2(1 - p)
def huffman_bloques(p, k):
"""Huffman sobre los 2^k bloques de una fuente binaria con P(a) = p. Devuelve (código, probabilidades)."""
probs = {}
for bloque in product("ab", repeat=k):
nb = bloque.count("b")
probs["".join(bloque)] = p ** (k - nb) * (1 - p) ** nb
return huffman(probs), probs
p = 0.95
print(f"h2({p}) = {h2(p):.4f} bits por símbolo")
for k in range(1, 9):
codigo, probs = huffman_bloques(p, k)
L = sum(probs[b] * len(codigo[b]) for b in probs)
print(f"k = {k}: L_k/k = {L / k:.4f} exceso = {L / k - h2(p):.4f} cota 1/k = {1 / k:.4f} palabras = {len(codigo)}")
# medido: 20 000 símbolos reales codificados por bloques de 4
rng = np.random.default_rng(0)
seq = "".join(rng.choice(["a", "b"], size=20_000, p=[p, 1 - p]))
codigo, _ = huffman_bloques(p, 4)
bits = sum(len(codigo[seq[i:i + 4]]) for i in range(0, len(seq), 4))
print(f"\nsecuencia de {len(seq)} símbolos, bloques de 4: {bits / len(seq):.4f} bits por símbolo (sin bloques: 1.0000)")The table matches the preceding figure. The measurement on a concrete sequence, bits per symbol, is close to theory (), with expected sample fluctuation. With we already go below one bit per symbol to just over a third.
The library version
In production nobody writes their own Huffman: they use zlib (DEFLATE: LZ77 followed by Huffman), bz2 (Burrows–Wheeler transform and Huffman) or lzma. What matters is what can be isolated. The standard library lets zlib use only the Huffman stage, without searching for repetitions (Z_HUFFMAN_ONLY), equivalent to the order-0 code just written. Comparing the two with the full compressor measures the value, beyond Huffman, of exploiting text structure.
import bz2, lzma, zlib
def deflate_huffman(datos):
"""DEFLATE con la etapa de LZ77 desactivada: solo códigos de Huffman por bloque."""
c = zlib.compressobj(9, zlib.DEFLATED, -15, 9, zlib.Z_HUFFMAN_ONLY)
return len(c.compress(datos) + c.flush())
H = entropia_bytes(largo)
print(f"Texto de {len(largo)} bytes; entropía de orden 0 = {H:.3f} bits/símbolo -> cota {H * len(largo) / 8:.0f} bytes\n")
resultados = [
("Huffman propio (cabecera incluida)", len(comprime(largo)[0])),
("zlib solo Huffman (Z_HUFFMAN_ONLY)", deflate_huffman(largo)),
("zlib completo (LZ77 + Huffman)", len(zlib.compress(largo, 9))),
("bz2", len(bz2.compress(largo, 9))),
("lzma", len(lzma.compress(largo))),
]
for nombre, tam in resultados:
print(f"{nombre:38s} {tam:7d} bytes {8 * tam / len(largo):.3f} bits/símbolo")The custom Huffman and zlib Huffman stay close to the order-0 bound, as expected: the same kind of code applied to the same frequencies ( and bytes versus a bound of ). The -byte difference mainly comes from DEFLATE describing its table with fewer bytes and adapting a code to each block. The other compressors go well below order-0 entropy: full zlib gives bits per symbol, and bz2 and lzma , less than half of . They violate no theorem: bound applies to a code encoding each byte independently using global frequencies; a source with memory (text repeats words, code repeats structures) has a much lower entropy rate (entropy rate, lesson 4), and LZ77 and BWT exploit that memory (Lempel–Ziv coding).
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 3. How many leaves of descend from word , at depth ?
More than one answer may be correct.
Step 1 of 3. There is an optimal code where the two least probable symbols are siblings at maximum depth. What exchange justifies this?
huffman_longitudes(p), which receives a list of positive probabilities (or weights) and returns the list of Huffman codeword lengths in the same order as the input. For a single symbol return [0]. Tests check that the Kraft sum is 1, mean length matches exhaustive search on small alphabets, and input order is respected.import heapq
def huffman_longitudes(p):
"""Longitudes del código de Huffman para los pesos p, en el orden de la entrada."""
n = len(p)
# tu código: una cola de prioridad con (peso, desempate, índices de los símbolos del árbol)
return [0] * nSummary
- Codes. Nonsingular, UD and prefix are nested classes. Prefix codes decode on the fly and are trees whose words are leaves.
- Kraft–McMillan. A prefix code with lengths exists if and only if (proof with the depth- tree and canonical construction), and UD codes satisfy the same condition, so add nothing new.
- Redundancy identity. , with . It gives , equality only for dyadic and, with , bound . With -symbol blocks, excess per symbol falls below .
- Huffman. Repeatedly merging the two lightest nodes gives an optimal code, by an exchange lemma and a reduction lemma. Mean length is the sum of internal-node weights. Cost with a heap.
- Wrong model. Lengths with data from cost : cross entropy is a code length and divergence its extra cost.
- Limits. A symbol-by-symbol code never goes below one bit per symbol, and Huffman loses nearly one bit with highly biased sources. Blocks fix this at the cost of an exponential table, and arithmetic coding (lesson 7) fixes it without a table.
- Practice. A real compressor sends lengths, not trees (canonical codes), and the header counts.
zlibwithZ_HUFFMAN_ONLYisolates DEFLATE’s Huffman stage.