Sub topic 2
Counting Symbols: Frequencies and Probabilities
This chapter assumes you can read basic Python and know what a fraction or proportion is. Huffman coding never looks at what a symbol means. Its only input is a table that says how often each symbol appears. Getting that table right comes before any tree building.
Frequencies and Probabilities
A symbol is one unit that the coder will replace with a bit pattern. It might be a character, a byte, or a token from an earlier compression stage. The set of all symbols that can occur is the alphabet.
A symbol's frequency is the number of times it appears in the message. Its probability is that frequency divided by the message length. Take the 11-character string abracadabra:
| Symbol | Frequency | Probability |
|---|---|---|
| a | 5 | 0.455 |
| b | 2 | 0.182 |
| r | 2 | 0.182 |
| c | 1 | 0.091 |
| d | 1 | 0.091 |
The probabilities add up to 1. Huffman's algorithm gives the same tree whether you use counts or probabilities, because dividing every count by the same number keeps their order unchanged. Implementations usually use integer counts to avoid floating-point rounding.
The skew in this chart is what compression uses. If a gets a short code, the saving counts five times. If d gets a long code, the cost counts only once.
Counting in Python
collections.Counter builds the table in one pass:
from collections import Counter
def symbol_stats(text):
freq = Counter(text)
n = len(text)
return {sym: (f, f / n) for sym, f in freq.most_common()}
for sym, (f, p) in symbol_stats("abracadabra").items():
print(f"{sym!r}: count={f}, p={p:.3f}")Output:
'a': count=5, p=0.455
'b': count=2, p=0.182
'r': count=2, p=0.182
'c': count=1, p=0.091
'd': count=1, p=0.091Common Errors
- Counting the wrong unit. A Python
strcontains Unicode characters, but files are stored as bytes.Counter("café")counts 4 symbols, whileCounter("café".encode("utf-8"))counts 5 integers, becauseétakes two bytes. Byte-oriented compressors count bytes, so they use an alphabet of at most 256 symbols. - Treating ties as unimportant.
bandrhave the same count. Which one gets merged first changes the bit patterns, though it does not change the total encoded length. The encoder and the decoder must break ties the same way. Later chapters handle this with a tie-breaker counter and with canonical codes. - Leaving out symbols that never appear. A symbol with count 0 gets no code. That is fine for a static code built from the whole message. It breaks when you build the table from a sample and later encode data that contains new symbols.
- Edge-case inputs. An empty message has no table at all. A message with only one distinct symbol, such as
"aaaa", gives a table with one entry, and a tree with one leaf has no edges to label with bits. Code that builds Huffman codes has to handle both cases on purpose.
Exercises
Exercise
Build the frequency and probability table for "mississippi". Which symbol or symbols should get the shortest code?
Show answer
The string has 11 characters: i = 4 (0.364), s = 4 (0.364), p = 2 (0.182), m = 1 (0.091). The letters i and s are the most frequent, so they should get the shortest codes. They are tied, so a consistent tie-breaking rule decides their exact bit patterns.
Exercise
The data is a UTF-8 file containing "naïve". How many symbols does a byte-oriented compressor count, and how many does Counter on the decoded string count?
Show answer
A byte-oriented compressor counts 6 symbols, because "ï" takes two bytes in UTF-8. Counter on the decoded string counts 5 symbols: n, a, ï, v, e.