Sub topic 2
Counting Symbols: Frequencies and Probabilities
Huffman coding starts with a table that says how often each symbol occurs, and the code it builds can only be as good as that table. This chapter covers how to build the table: what counts as a symbol, how to count, how to convert counts into probabilities, and which edge cases break the algorithm later if you ignore them now.
This chapter assumes you can read and run basic Python, know that a byte is 8 bits, and are comfortable with proportions such as "5 out of 11".
What a Symbol Is
A symbol is the unit the coder assigns a codeword to. The alphabet is the set of all symbols that can appear. The choice of symbol is a design decision, and each common choice has costs:
| Symbol unit | Alphabet size | Typical use | Trade-off |
|---|---|---|---|
| Byte (0–255) | 256 | General-purpose file compressors | Works on any file and keeps the table small, but ignores structure across bytes |
| Unicode character | Up to about 1.1 million | Teaching examples, text-only tools | Feels natural for text, but you must encode to bytes consistently afterwards |
| Word or token | Unbounded | Specialized text compression | Captures more structure, but the code table gets large |
| Derived symbol | Format-defined | DEFLATE literal/length codes, JPEG run/size pairs | Comes from an earlier modeling stage rather than raw input |
Most examples in this tutorial use characters of a short string because the output is easy to read. Real compressors count bytes or derived symbols. If you mix the two by counting characters but writing bytes, you get bugs, and the section on common errors below covers them.
Counting with `Counter`
Python's collections.Counter maps each symbol to the number of times it appears. A frequency is that raw count.
from collections import Counter
text = "abracadabra"
freq = Counter(text)
n = len(text)
print(freq)
for sym, f in freq.most_common():
print(f"{sym!r}: count={f}, probability={f / n:.3f}")Output:
Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
'a': count=5, probability=0.455
'b': count=2, probability=0.182
'r': count=2, probability=0.182
'c': count=1, probability=0.091
'd': count=1, probability=0.091The probability of a symbol is its count divided by the total number of symbols: p(s) = f(s) / n. The probabilities always sum to 1. Here they are 5/11, 2/11, 2/11, 1/11 and 1/11.
| Symbol | Count f(s) | Probability p(s) |
|---|---|---|
| a | 5 | 5/11 ≈ 0.455 |
| b | 2 | 2/11 ≈ 0.182 |
| r | 2 | 2/11 ≈ 0.182 |
| c | 1 | 1/11 ≈ 0.091 |
| d | 1 | 1/11 ≈ 0.091 |
| Total | 11 | 1 |
The two ties, b with r and c with d, matter later. Huffman's algorithm has to pick between equal-weight nodes, and different tie-breaking rules produce different trees that compress equally well. This is why the tutorial's heap-based builder adds a counter as a tie-breaker.
Counts or Probabilities: Which to Feed the Algorithm
Huffman's algorithm only compares and adds weights, and scaling every weight by the same positive factor leaves every comparison unchanged. Counts and probabilities therefore produce the same tree. In practice, prefer integer counts:
- Integer addition is exact. Floating-point sums such as 0.1 + 0.2 can produce rounding noise, which can flip a tie and give a different (equally good) tree on another platform. A different tree is a real problem when the decoder has to rebuild the encoder's code exactly.
- Counts are what you store or transmit. Probabilities are only needed for analysis, such as the entropy calculation in a later chapter.
If you need exact probabilities for analysis, fractions.Fraction avoids rounding:
from collections import Counter
from fractions import Fraction
text = "abracadabra"
freq = Counter(text)
n = sum(freq.values())
probs = {s: Fraction(f, n) for s, f in freq.items()}
print(probs)
assert sum(probs.values()) == 1Why Frequencies Determine Compressed Size
Once each symbol s has a codeword of length L(s) bits, the total output size is the count-weighted sum of the lengths:
total bits = Σ f(s) · L(s)
Dividing by n gives the average bits per symbol, Σ p(s) · L(s). This is the expected code length. It shows why frequent symbols need short codes: each bit you save on a frequent symbol is saved f(s) times.
from collections import Counter
def total_bits(freq, lengths):
return sum(freq[s] * lengths[s] for s in freq)
text = "abracadabra"
freq = Counter(text)
n = len(text)
fixed = {s: 3 for s in freq} # 5 symbols need 3 bits each
variable = {"a": 1, "b": 3, "r": 3, "c": 3, "d": 3}
for name, lengths in [("fixed", fixed), ("variable", variable)]:
bits = total_bits(freq, lengths)
print(f"{name}: {bits} bits, {bits / n:.3f} bits/symbol")Output:
fixed: 33 bits, 3.000 bits/symbol
variable: 23 bits, 2.091 bits/symbolGiving a a 1-bit code saves 2 bits five times, which adds up to 10 bits. Giving the same lengths to the wrong symbols, for example a 1-bit code to d, would save far less. The frequency table is what tells you which assignment helps. The variable-length table above is also prefix-free-feasible, meaning a prefix-free code with those lengths exists. The prefix-free requirement and how to check it are covered in the next chapter.
Where the Counts Come From
The same data can be modeled with frequencies from different sources:
- Exact counts from the message itself. The encoder reads the input once to count and a second time to encode. The code fits this data best, but the decoder needs the table, so it has to be shipped with the data. A later chapter covers how.
- A fixed table agreed in advance. Both sides use frequencies (or code lengths) defined by a standard. Nothing is transmitted, but the fit is worse when the data differs from what the table assumed. DEFLATE's fixed-code blocks and JPEG's example tables work this way.
- Counts updated while coding. Adaptive schemes adjust frequencies as symbols arrive and need only one pass. They have their own chapter.
Counting over a sample instead of the full data is a version of option 2, and it carries the risk described next.
Edge Cases That Break Later Stages
Zero-frequency symbols
Counter only contains symbols that occurred. That is fine when you count the exact message, because absent symbols never need a code. It fails when you build a code from a sample and then encode different data:
from collections import Counter
sample_freq = Counter("abracadabra")
message = "abracadabra!"
missing = set(message) - set(sample_freq)
print(missing) # {'!'} -> no codeword exists for this symbolThe usual fix is to give every symbol in the full alphabet a small nonzero count, often called add-one smoothing. The cost is a slightly longer code for the symbols that do appear.
from collections import Counter
def smoothed_byte_counts(data: bytes):
freq = Counter(data)
return {b: freq.get(b, 0) + 1 for b in range(256)}
counts = smoothed_byte_counts(b"abracadabra")
print(len(counts), counts[ord("a")], counts[ord("!")]) # 256 6 2Empty and single-symbol input
An empty input gives an empty table, and no tree can be built from it. Handle that case before building the tree and emit an empty output. An input with only one distinct symbol gives a tree with a single leaf and a path length of zero, which means a zero-bit code. The builder in the next chapters assigns "0" in this case, and the decoder must also know the message length to know when to stop.
An end marker
If the decoder cannot learn the message length any other way, add a dedicated end-of-data symbol with count 1 to the table. DEFLATE does this: symbol 256 in its literal/length alphabet marks the end of a block.
s = "naïve café"
print(len(s), len(s.encode("utf-8"))) # 10 12
print(Counter(s.encode("utf-8")).most_common(3))This last snippet needs from collections import Counter if you run it on its own.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Counting characters, encoding bytes | `KeyError` on non-ASCII input | Count `data: bytes` throughout |
| Building codes from a sample | Missing codeword for an unseen symbol | Smooth over the full alphabet |
| Float probabilities as weights | Encoder and decoder trees differ across platforms | Use integer counts |
| Ignoring empty input | Crash when popping from an empty heap | Return early |
| No length or end marker | Decoder emits extra symbols from padding bits | Store n or add an end symbol |
Exercise
Count the symbols in "mississippi". Give each count and probability, then compute the total bits for a fixed 2-bit code and for a code with lengths i:1, s:2, p:3, m:3.
Show answer
Counts are i=4, s=4, p=2, m=1, so n=11, with probabilities 4/11, 4/11, 2/11 and 1/11. The fixed 2-bit code uses 11 × 2 = 22 bits. The variable code uses 4·1 + 4·2 + 2·3 + 1·3 = 21 bits, about 1.909 bits per symbol. Giving s the 1-bit code instead also costs 21 bits, because i and s are tied.
Exercise
You build a Huffman code from counts of English text and use it to compress a file containing a tab character that never appeared in your sample. What goes wrong, and give two ways to prevent it.
Show answer
The tab has no codeword, so the encoder cannot represent it and fails with a KeyError or something similar. You can count the actual file being compressed and ship its table, or you can smooth the sample counts so every symbol in the alphabet (for example all 256 byte values) has a count of at least 1.