IT·02
Counting Possibilities: Bits, Logarithms and Questions
How to count what a message could have been, and turn the count into bits: sequences (the multiplication principle), orderings (factorials) and choices (combinations); logarithms as the tool that turns those counts into information; fixed-length codes from the telegraph's 5-bit Baudot code to 7-bit ASCII; grouping symbols into blocks to waste fewer binary digits; question strategies as binary trees; and the information-theoretic reason no comparison sort can beat about n log₂ n comparisons, checked against Python's own sort.
Start here
What this chapter answers
How many possible passwords, card hands, shuffles or lottery draws are there, and how many bits does each carry? Why does a code for 26 letters need 5 binary digits, and why does that waste some of them? How can you waste less without any probability at all? What do yes-or-no questions have to do with binary trees? And why can no sorting method that compares items do much better than comparisons, however clever it is?
Counting in one picture
A café offers 3 mains, 4 drinks and 2 desserts, and a meal is one of each. To tell the kitchen which meal you want, you're picking one of possibilities, so your order carries bits. The kitchen could number the 24 meals and you could send the number in 5 binary digits (). Or you could send the main in 2 digits, the drink in 2 and the dessert in 1, also 5. Both work; both "waste" a little, since 5 is more than 4.58. Counting the possibilities gives the information; rounding up to whole binary digits gives the cost of a fixed-length code. This chapter is about both numbers and the gap between them.
Counting possibilities
Sequences: the multiplication principle
If a first choice has options and, whatever it was, a second has , then the pair has possibilities. Repeating this gives the multiplication principle: a sequence of symbols, each chosen from an alphabet of , has
possibilities. A 4-digit PIN has ; an 8-character password from the 94 printable keyboard symbols has ; an IPv4 address of 32 binary digits has billion.
Because , the information in such a sequence is times the information in one symbol: the password carries bits. Information grows linearly with length while the number of possibilities grows exponentially, which is the whole reason a logarithm is the right measure.
Orderings: factorials
How many ways can different things be put in order? The first place has choices, the second (one thing is used), and so on down to 1:
Three people can queue in ways; a deck of 52 cards can be shuffled into orders, so a well-shuffled deck carries bits. That number has a practical consequence: a card game that shuffles using a random number generator with a 32-bit seed can only ever produce of those orders, a vanishing fraction, and anyone who learns the seed knows every card. A widely reported 1999 analysis of an online poker site did exactly that.
Choices: combinations
How many ways can you choose things from , when the order of choosing doesn't matter? Count ordered choices (), then divide by the orders in which each set could have been picked:
read " choose ". A 5-card hand from 52 is one of (21.3 bits); a 6-from-49 lottery draw one of (23.7 bits, chapter 1's jackpot). These binomial coefficients come back in chapter 6: is the number of strings of binary digits with exactly ones, and its logarithm is how the source coding theorem is proved.
From counts to bits
Every count above becomes information through , and three rules (Mathematics Book 1, chapter 10) do almost all the work:
| Rule | In symbols | What it means here |
|---|---|---|
| Products become sums | Independent choices' bits add | |
| Powers become multiples | symbols carry times one symbol's bits | |
| Quotients become differences | Ruling out possibilities subtracts bits |
For estimates in your head, use : so , , , and . A billion possibilities is about 30 bits; 8 billion is about 33.
Fixed-length codes
One symbol at a time
A fixed-length code gives every symbol of an alphabet a string of the same number of binary digits. With symbols you need digits where , so
Baudot's 5 digits give 32 codes; ASCII's 7 give 128. Twenty-six capital letters need 5 (since ), and the 65 different bytes in the chapter's Shakespeare file need 7. Fixed-length codes are simple to decode: cut the stream every digits, and each piece is a symbol. That's why machines use them.
The cost is the rounding. A letter from 26 equally likely ones carries bits, but the code spends 5: six of the 32 codes are never used, and of a binary digit per letter is wasted. The efficiency of a code is information carried divided by digits spent: . For decimal digits it's worse: each carries bits, but needs 4 binary digits, so 83 % efficiency (binary-coded decimal, used in old calculators and some financial hardware, pays exactly this).
Grouping symbols into blocks
The waste comes from rounding up once per symbol. Round up once per group instead. Three decimal digits have possibilities, which fit in 10 binary digits (): digits per decimal digit instead of 4, almost exactly . In general, a block of symbols from needs digits, and since the rounding loses less than one digit per block,
So longer blocks get as close to as you like. This is the first appearance of the most important trick in the book: coding many symbols together beats coding them one at a time. Chapter 6 uses it, with probabilities, to prove that entropy is the limit of compression. The lab shows that the improvement isn't steady: some block lengths fit a power of two much better than others.
Questions as trees
A strategy is a binary tree
Any plan of yes-or-no questions can be drawn as a binary tree. The root is the first question; its two branches lead to the next question for each answer; and each leaf is a point where the answer is known. Reading the answers along the path from the root to a leaf, writing 1 for yes and 0 for no, gives a string of binary digits that identifies that outcome: a codeword. So a question strategy and a code are the same thing. The number of questions to reach an outcome is the depth of its leaf, which is the length of its codeword.
A tree of depth has at most leaves, so a strategy that must distinguish outcomes has some leaf at depth at least : the chapter 1 bound, in a picture. A fixed-length code is a tree with all its leaves at the same depth. Chapter 5 will let the leaves sit at different depths, likely outcomes near the root, and that's how compression works.
The sorting lower bound
Sorting is a question game. A comparison sort learns about its input only by asking "is item less than item ?", one yes-or-no question at a time, and it must end up knowing which of the possible orders the input was in (otherwise two inputs in different orders would be rearranged the same way, and one of them would come out unsorted).
How big is ? Using Stirling's approximation ,
So every comparison sort needs about comparisons, and merge sort, heap sort and Python's own sort achieve that, up to a small factor. This is why "" is the speed limit you meet in algorithms courses (Software Engineering, Volume 1, chapter 4): it isn't a property of any particular algorithm but of the information a sort must gather, bits, one bit per comparison at best. Sorts that beat it, such as counting sort and radix sort, do so by asking questions with more than two answers (which bucket does this digit go in?).
Lab: counting, packing and sorting
Experiment 1: how many bits in everyday choices
import math
cases = [("a 4-digit PIN", 10 ** 4),
("an 8-character password from 94 printable symbols", 94 ** 8),
("a hand of 5 cards from 52", math.comb(52, 5)),
("the order of a shuffled 52-card deck", math.factorial(52)),
("a 6-from-49 lottery draw", math.comb(49, 6)),
("an IPv4 address", 2 ** 32),
("an IPv6 address", 2 ** 128)]
for name, n in cases:
print(f"{name:<52} {n:.4g} possibilities = {math.log2(n):7.2f} bits")
a 4-digit PIN 1e+04 possibilities = 13.29 bits
an 8-character password from 94 printable symbols 6.096e+15 possibilities = 52.44 bits
a hand of 5 cards from 52 2.599e+06 possibilities = 21.31 bits
the order of a shuffled 52-card deck 8.066e+67 possibilities = 225.58 bits
a 6-from-49 lottery draw 1.398e+07 possibilities = 23.74 bits
an IPv4 address 4.295e+09 possibilities = 32.00 bits
an IPv6 address 3.403e+38 possibilities = 128.00 bits
A PIN carries 13.3 bits and a random 8-character password 52.4; a 5-card hand 21.3 and a lottery draw 23.7. A shuffled deck carries 225.6 bits, more than an IPv6 address (128): there are more ways to shuffle a deck than there are IPv6 addresses, by a factor of about .
Experiment 2: block coding gets closer to log₂ K
import math
def best_block(k, max_len=12):
"""For an alphabet of k symbols, bits per symbol when coding blocks of length L with a fixed-length code."""
rows = []
for L in range(1, max_len + 1):
bits = math.ceil(L * math.log2(k) - 1e-12) # ceil(log2(k**L))
assert 2 ** bits >= k ** L > 2 ** (bits - 1)
rows.append((L, bits, bits / L))
return rows
for name, k in (("decimal digits", 10), ("die rolls", 6), ("letters A-Z", 26)):
rows = best_block(k)
shown = ", ".join(f"{L}->{b / L:.3f}" for L, b, _ in rows if L in (1, 2, 3, 5, 10, 12))
print(f"{name:<15} log2 {k} = {math.log2(k):.4f}; bits per symbol by block length: {shown}")
decimal digits log2 10 = 3.3219; bits per symbol by block length: 1->4.000, 2->3.500, 3->3.333, 5->3.400, 10->3.400, 12->3.333
die rolls log2 6 = 2.5850; bits per symbol by block length: 1->3.000, 2->3.000, 3->2.667, 5->2.600, 10->2.600, 12->2.667
letters A-Z log2 26 = 4.7004; bits per symbol by block length: 1->5.000, 2->5.000, 3->5.000, 5->4.800, 10->4.800, 12->4.750
One decimal digit at a time costs 4 binary digits; blocks of 3 cost 3.333 per digit (1000 in 1024), within 0.012 of . The improvement isn't monotone: blocks of 5 digits cost 3.4, worse than blocks of 3, because sits just above and needs 17 digits. Die rolls do best in blocks of 5 ( , so 2.6 per roll against ). The bound guarantees that as blocks lengthen, the cost falls below , but for a particular length the fit can be lucky or unlucky.
Experiment 3: Python's sort against the information limit
import functools, math, random
random.seed(52)
class Counted:
calls = 0
def __init__(self, v): self.v = v
def __lt__(self, other):
Counted.calls += 1
return self.v < other.v
for n in (10, 100, 1000, 10_000):
xs = [Counted(random.random()) for _ in range(n)]
Counted.calls = 0
sorted(xs)
bound = math.lgamma(n + 1) / math.log(2) # log2(n!)
print(f"n = {n:>6}: log2(n!) = {bound:>10,.0f} Python's sort used {Counted.calls:>10,} comparisons ratio {Counted.calls / bound:.3f}")
n = 10: log2(n!) = 22 Python's sort used 25 comparisons ratio 1.147
n = 100: log2(n!) = 525 Python's sort used 540 comparisons ratio 1.029
n = 1000: log2(n!) = 8,529 Python's sort used 8,665 comparisons ratio 1.016
n = 10000: log2(n!) = 118,458 Python's sort used 120,177 comparisons ratio 1.015
Wrapping the items in a class that counts calls to < lets us count every comparison Python's built-in sort makes (math.lgamma(n + 1) is , divided by to give ). On shuffled data, Python's sort uses only 1.5 % more comparisons than the information-theoretic minimum for 10,000 items: 120,177 against 118,458. No comparison sort can do better than the minimum in the worst case, and Python's comes within a whisker of it on random input. (On input that's already partly sorted, it uses far fewer, because such input carries less than bits of "which order is this?": chapter 4's entropy again.)
Experiment 4: a fixed-length code for Shakespeare
import math
def pack(values, width):
"""Write each value in `width` binary digits, most significant first, into bytes."""
out, acc, n = bytearray(), 0, 0
for v in values:
acc, n = (acc << width) | v, n + width
while n >= 8:
n -= 8
out.append((acc >> n) & 0xFF)
acc &= (1 << n) - 1
if n:
out.append((acc << (8 - n)) & 0xFF) # pad the last byte with zeros
return bytes(out)
def unpack(packed, width, count):
values, acc, n, it = [], 0, 0, iter(packed)
while len(values) < count:
while n < width:
acc, n = (acc << 8) | next(it), n + 8
n -= width
values.append((acc >> n) & ((1 << width) - 1))
acc &= (1 << n) - 1
return values
data = open("data/shakespeare.txt", "rb").read()
alphabet = sorted(set(data))
width = math.ceil(math.log2(len(alphabet)))
index = {b: i for i, b in enumerate(alphabet)}
packed = pack([index[b] for b in data], width)
restored = bytes(alphabet[i] for i in unpack(packed, width, len(data)))
print(f"{len(alphabet)} distinct bytes -> {width} binary digits each")
print(f"original {len(data):,} bytes, packed {len(packed):,} bytes ({8 * len(packed) / len(data):.3f} bits per byte)")
print("round trip exact:", restored == data)
65 distinct bytes -> 7 binary digits each
original 1,115,394 bytes, packed 975,970 bytes (7.000 bits per byte)
round trip exact: True
The plays use 65 different byte values, so each fits in 7 binary digits. The program numbers the 65 symbols, writes each number in 7 digits into a stream of bytes (a bit writer), and reads them back: 1,115,394 bytes become 975,970, an exact round trip. Saving one digit in eight is all a fixed-length code can do here; chapter 1's lzma got to 2.6 bits per character by exploiting unequal frequencies and context, which fixed-length codes ignore. The bit writer itself is reused by every later chapter and by the capstone.
Worked examples
Counting and bits
A code for a keypad
The sorting bound for small n
Exercises
Practice
- How many 6-character strings are there from the lowercase letters and digits (36 symbols)? How many bits?
- In how many orders can 10 books be put on a shelf? How many bits is that?
- How many ways can a committee of 4 be chosen from 12 people? How many bits?
- How many binary digits does a fixed-length code need for: the 4 DNA bases; the 20 amino acids; the 128 ASCII characters; 1,000 product codes?
- Use to estimate of 4 million and of 2 trillion.
- What's the efficiency of a fixed-length code for 20 equally likely amino acids, one at a time? In blocks of 3?
- What's the minimum worst-case number of comparisons to sort 6 items?
Answers
- ; bits.
- ; bits.
- ; bits.
- 2; 5; 7; 10.
- , so about 22 (exactly 21.93). , so about 41 (exactly 40.86).
- bits in 5 digits: 86.4 %. Blocks of 3: , so 13 digits for 3 acids, 4.333 each: 99.7 %.
- .
Harder
- Explain, using the multiplication principle, why , and why .
- A website issues 6-digit verification codes that expire after 10 minutes and allows 5 attempts. What's an attacker's chance of guessing one code? How many bits of information does a code carry, and how many does the attacker effectively get to "try"?
- Show that for every , without Stirling's formula. Then show it's at least .
- Why does counting sort, which sorts numbers between 0 and 999 in about steps, not contradict the sorting lower bound?
- A sensor sends readings 0 to 99 as two ASCII digits (16 binary digits). Propose a fixed-length code for blocks of readings that gets within 1 % of the information limit, and say how many readings per block.
Answers
- Choosing the items to take is the same as choosing the to leave, so the counts match. For the sum: each of the subsets of items (each item in or out, multiplication principle) has some size , and there are subsets of each size.
- in 200,000. A code carries bits; 5 guesses cover bits' worth of possibilities, leaving about 17.6 bits the attacker can't get through. (Their success chance is .)
- , so . For the lower bound, the top half of the factors, from about to , are each at least , and there are at least of them, so . So is between and : it grows like .
- Counting sort doesn't learn about the input by comparisons. It asks "which of 1000 values is this?", a question with 1000 answers, worth up to bits each, so such questions can gather bits, plenty for when is moderate. The lower bound only applies to methods restricted to two-answer comparisons.
- Each reading carries bits. Blocks of 3: , 20 digits for 3 readings, 6.667 each: 99.65 % efficiency. One reading at a time needs 7 (94.9 %); ASCII spends 16 (41.5 %).
Challenge
- Ralph Hartley's 1928 measure was for symbols from an alphabet of . A telegraph line sends 50 symbols a second from Baudot's 32-symbol alphabet. What's its rate in bits per second? If letters arrived with English frequencies instead of equally likely, would the true information rate be higher or lower, and why doesn't Hartley's measure see it?
Discussion
bits per second. With English text, the symbols aren't equally likely (letters vary from 12 % to 0.07 %, chapter 1), and each depends on the ones before, so the information per symbol is less than bits: perhaps 1 to 2 bits per letter with context (chapter 10 measures it). The line's capacity to carry information is 250 bits per second, but the English source fills only a fraction of it. Hartley's measure counts possibilities, as if all were equally likely; it measures the line, not the message. Shannon's entropy (chapter 4) measures the message, and the gap between the two is what compression recovers.
In real life
Misconceptions and limits
The model to keep
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Doubling a password's length doubles the number of passwords." | It squares it; it doubles the bits. | Sequences: the multiplication principle |
| "A code for K symbols needs log₂ K binary digits." | One at a time it needs ; only blocks approach . | Fixed-length codes |
| "Longer blocks always do better." | Not always: decimal blocks of 5 cost more than blocks of 3. | Experiment 2 |
| "O(n log n) sorting is a fact about merge sort." | It's a fact about the information any comparison sort must gather. | The sorting lower bound |
| "Counting sort breaks the sorting lower bound." | It asks questions with many answers, not comparisons. | Harder exercise 11 |
| "The information bound can always be achieved exactly." | It's a floor: sorting 12 items needs 30 comparisons, not 29. | Worked example, the sorting bound |
| "A random generator can produce any shuffle." | Not if its seed has fewer than 226 bits. | Orderings: factorials |
| "Fixed-length codes can compress text a lot." | Only by the rounding: 8 to 7 bits for Shakespeare; compression needs probabilities. | Experiment 4 |
Limits and trade-offs
- Equally likely is an assumption. Counting gives the information only when every possibility is equally likely. Real messages aren't, and chapter 4's entropy replaces with an average that weights each outcome by its probability.
- Fixed-length codes trade size for simplicity. They can be decoded at any position (symbol starts at digit ), which variable-length codes can't; that random access is why databases and CPUs prefer them.
- Blocks add delay and complexity. Coding 5 die rolls at once means waiting for 5 rolls before sending anything, and the encoder's tables grow as .
Revision sheet
Key ideas
- Multiplication principle: choices from each give sequences; bits add: .
- Factorial: orders; bits in a shuffled deck.
- Combinations: ways to choose from .
- Estimating: ; .
- Fixed-length code: digits per symbol; efficiency = ÷ digits.
- Blocks: symbols in digits; under per symbol.
- Question strategies are binary trees; a codeword is the path; depth = questions.
- Sorting bound: any comparison sort needs comparisons in the worst case.
- Stirling: .
Glossary
- Multiplication principle: if one choice has options and a second has whatever the first was, together they have .
- Factorial: , the number of orders of different things.
- Binomial coefficient: , the number of ways to choose things from when order doesn't matter.
- Fixed-length code: a code giving every symbol a codeword of the same number of binary digits.
- Codeword: the string of symbols a code assigns to one message or symbol.
- Code efficiency: the information a code carries per symbol divided by the binary digits it spends per symbol.
- Block coding (of a source): encoding several source symbols together as one, so rounding costs less per symbol.
- Bit writer: code that packs values of any number of binary digits into a stream of bytes, and its reader unpacks them.
- Decision tree: a binary tree drawing a strategy of yes-or-no questions, with an outcome at each leaf.
- Comparison sort: a sorting method that learns about its input only by comparing pairs of items.
- Sorting lower bound: the fact that any comparison sort needs at least comparisons in the worst case.
- Stirling's approximation: , so .
- ASCII: the American Standard Code for Information Interchange (1963), a 7-bit fixed-length code for 128 characters.