Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·02

Counting Possibilities: Bits, Logarithms and Questions

Around chapter 2: how counting, fixed-length codes and question trees connect to the rest of the book; three other ways to see them; what the chapter simplifies (the sorting bound is about the worst input, blocks as long as the message hit a speed limit, and duplicates carry less information than a sort exploits); how Python's shuffle spends 380 random bits on a 226-bit shuffle; four debugging drills; and interview questions.

6 topics · ~16 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Counting (chapter 2): sequences kn, orders n!, choices (nr) → log2 of the count is the information when all are equally likely (chapter 1).
  • Logarithm rules → bits add for independent choices, multiply with length, subtract when possibilities are ruled out.
  • Fixed-length codes ⌈log2K⌉ → efficiency → blocks approach log2K → chapter 6 does the same with probabilities and reaches entropy.
  • Question strategies = binary trees = codes → leaves at different depths (chapter 5, Huffman) → the Kraft inequality.
  • Sorting bound log2n! → algorithms that gather nearly a bit per comparison (merge sort) against those that don't (insertion sort) → inputs with structure carry fewer bits (point 1 below; chapter 4).
  • Binomial coefficients → strings with r ones → chapter 6's typical sequences.

Explain it differently

A combination lock as a slot machine. Each wheel of a lock is a reel with k symbols; n wheels give kn settings. Adding a wheel multiplies the settings but adds the same number of bits, so a thief's work doubles for every extra bit, however many wheels there already are.

A filing cabinet with fixed drawers. A fixed-length code is a cabinet where every drawer is the same size: easy to find drawer number 1,000 (it's at position 1000×L), but drawers sized for the biggest item waste space on the small ones. Blocks are like sharing drawers between neighbours: less waste, but to fetch one item you open a drawer that holds several.

The detective's notebook. A detective with n! suspects (every possible order of events) asks witnesses yes-or-no questions. Each answer at best halves the suspects. A good question is one whose answer the detective can't guess; a question with a predictable answer (insertion sort's "is the item I just placed bigger than its neighbour?") eliminates almost no one.

Gaps and misconceptions

What the chapter oversimplifies

1. "Every comparison sort needs about nlog2n comparisons", which is about the worst input. The bound says some input needs log2n! comparisons. Inputs that are already partly in order carry less information about their order, and a good sort uses fewer:

Python
import math, random
random.seed(1)
class C:
    calls = 0
    def __init__(self, v): self.v = v
    def __lt__(self, o):
        C.calls += 1
        return self.v < o.v
n = 10_000
base = list(range(n))
nearly = base[:]
for _ in range(20):
    i, j = random.randrange(n), random.randrange(n)
    nearly[i], nearly[j] = nearly[j], nearly[i]
shuffled = random.sample(base, n)
for name, xs in (("shuffled", shuffled), ("already sorted", base), ("reversed", base[::-1]),
                 ("sorted, then 20 random swaps", nearly), ("two sorted halves", base[::2] + base[1::2])):
    C.calls = 0
    sorted(C(x) for x in xs)
    print(f"{name:<30} {C.calls:>8,} comparisons")
print(f"log2(n!) for n = {n:,}: {math.lgamma(n + 1) / math.log(2):,.0f}")
Text
shuffled                        120,240 comparisons
already sorted                    9,999 comparisons
reversed                          9,999 comparisons
sorted, then 20 random swaps     12,058 comparisons
two sorted halves                19,999 comparisons
log2(n!) for n = 10,000: 118,458

Python's sort uses 120,240 comparisons on shuffled input (just above log2n!=118,458), but only 9,999 on sorted or reversed input, 12,058 when 20 swaps disturbed a sorted list, and 19,999 for two sorted halves. The sort finds existing runs and merges them, so its work tracks how much the input's order is really uncertain. "Adaptive" sorting is measured against the information in the input's actual disorder, not against n!.

2. "Longer blocks approach log2K", and the longest block is the whole message. Treat an entire string of decimal digits as one number in base 10, and convert it to binary: the cost is ⌈nlog210⌉ digits for the whole string, the best a fixed-length method can do. Python can do it in one line, but not without limits:

Python
import random, sys, time
random.seed(2)
digits = "".join(random.choice("0123456789") for _ in range(10_000))
try:
    int(digits)
except ValueError as e:
    print("int() of 10,000 digits:", str(e)[:80], "...")
sys.set_int_max_str_digits(0)                      # remove the limit, as the error message suggests
for n in (10_000, 100_000, 1_000_000):
    s = (digits * (n // 10_000))[:n]
    t = time.perf_counter(); x = int(s); dt = time.perf_counter() - t
    print(f"{n:>9,} digits -> one integer of {x.bit_length():>9,} bits (n log2 10 = {n * 3.321928:>11,.0f}) in {dt:.3f} s")
Text
int() of 10,000 digits: Exceeds the limit (4300 digits) for integer string conversion: value has 10000 d ...
   10,000 digits -> one integer of    33,213 bits (n log2 10 =      33,219) in 0.007 s
  100,000 digits -> one integer of   332,187 bits (n log2 10 =     332,193) in 0.012 s
1,000,000 digits -> one integer of 3,321,922 bits (n log2 10 =   3,321,928) in 0.470 s

The integer is within a few bits of nlog210 every time: perfect block coding. But Python 3.11 and later refuse to convert more than 4,300 digits by default, because converting between bases took time growing with the square of the length, and attackers could send huge numbers to tie up servers (a denial-of-service fix, CVE-2020-10735). Newer Pythons use faster algorithms for huge numbers, but the cost still grows faster than the length (a million digits took about half a second). Coding a whole message as one block is the idea behind arithmetic coding and ANS (chapter 6), which get the same result with simple, steady per-symbol work.

3. "There are n! orders to tell apart", but only if the items are all different. With repeated values, many orders look the same; the number of distinguishable arrangements is n!c1!c2!⋯ (a multinomial coefficient), and a sort only needs that much information:

Python
import math, random
random.seed(3)
class C:
    calls = 0
    def __init__(self, v): self.v = v
    def __lt__(self, o):
        C.calls += 1
        return self.v < o.v
n = 10_000
for distinct in (n, 100, 10, 2):
    xs = [random.randrange(distinct) for _ in range(n)] if distinct < n else random.sample(range(n), n)
    counts = [xs.count(v) for v in set(xs)]
    orders = math.lgamma(n + 1) - sum(math.lgamma(c + 1) for c in counts)   # log of n! / (c1! c2! ...)
    C.calls = 0
    sorted(C(x) for x in xs)
    print(f"{len(counts):>6} distinct values: log2(distinguishable orders) = {orders / math.log(2):>9,.0f}   Python's sort: {C.calls:>8,} comparisons")
Text
 10000 distinct values: log2(distinguishable orders) =   118,458   Python's sort:  120,152 comparisons
   100 distinct values: log2(distinguishable orders) =    65,904   Python's sort:  102,919 comparisons
    10 distinct values: log2(distinguishable orders) =    33,161   Python's sort:   71,156 comparisons
     2 distinct values: log2(distinguishable orders) =     9,993   Python's sort:   47,949 comparisons

With 10,000 items taking only 2 values, the order carries just 9,993 bits (a choice of which positions hold which value), yet Python's sort still spends 47,949 comparisons: it doesn't exploit duplicates. Sorts that group equal keys (three-way partitioning quicksort, or counting sort for a few values) need much less. The multinomial coefficient's logarithm is about n times the entropy of the value frequencies, which is how chapter 4's entropy first appears in chapter 6's proof.

Common misconceptions

Misconception What's actually true Where it's shown
"Sorting always costs n log₂ n comparisons." Only for inputs with that much disorder; sorted input took 9,999. What the chapter oversimplifies, point 1
"Converting a big decimal number to binary is free." Python limits it to 4,300 digits by default; the cost grows faster than the length. What the chapter oversimplifies, point 2
"Sorting n items means telling apart n! orders." With duplicates there are far fewer: n!/(c₁! c₂! …). What the chapter oversimplifies, point 3
"A shuffle uses as many random bits as it has information." Python's spends about 380 bits on a 226-bit shuffle. Code walkthrough
"math.ceil(math.log2(n)) is always right." For n just above a large power of two, floating point rounds it wrong. Drill D1
"Compute a combination's bits from factorials." Dividing huge factorials as floats overflows; use math.comb or lgamma. Drill D2
"A number's digits survive a round trip through int." Leading zeros vanish unless the width is restored. Drill D3
"Swapping each item with a random position shuffles fairly." It makes nn equally likely paths onto n! orders, unevenly. Drill D4

Theoretical gaps: the ideas behind the chapter

  • The multinomial coefficient and entropy. log2n!c1!⋯ck!≈nH, where H is the entropy of the frequencies cin (Stirling, chapter 6). It's the number of bits needed to say which arrangement of a known multiset you have, and the bridge from counting to probability.
  • Kraft's inequality. A binary tree's leaves at depths d1,d2,… satisfy ∑2−di≤1, with equality when every internal node has two children. Fixed-length codes are the case where every di is equal; chapter 5 proves the inequality and uses it to design variable-length codes.
  • Adaptive sorting and presortedness. Measures of disorder (the number of runs, inversions, the length of the longest increasing subsequence) each define a smaller set of possible inputs; a sort is optimal for a measure if its comparisons match log2 of that set's size. Timsort and Powersort are near-optimal for runs.

Applying it

Code walkthrough

Python's random.shuffle is the Fisher–Yates shuffle (1938, in its computer form by Durstenfeld in 1964): for each position from the end, swap it with a random earlier or equal position. Excerpts from Lib/random.py in Python 3.13 (on your computer: python3 -c "import random; print(random.__file__)"):

Python
    def _randbelow_with_getrandbits(self, n):
        "Return a random int in the range [0,n).  Defined for n > 0."

        getrandbits = self.getrandbits
        k = n.bit_length()
        r = getrandbits(k)  # 0 <= r < 2**k
        while r >= n:
            r = getrandbits(k)
        return r

    def shuffle(self, x):
        """Shuffle list x in place, and return None."""

        randbelow = self._randbelow
        for i in reversed(range(1, len(x))):
            # pick an element in x[:i+1] with which to exchange x[i]
            j = randbelow(i + 1)
            x[i], x[j] = x[j], x[i]

The shuffle makes one choice among i+1 positions for each i from n−1 down to 1, so it picks one of n×(n−1)×⋯×2 =n! equally likely paths, each giving a different order: every order exactly once, which is why it's fair. Each choice needs log2(i+1) bits, so a whole shuffle needs log2n! bits of randomness, 225.6 for a deck.

_randbelow makes a fair choice among n with a fixed-length code: it draws n.bit_length() random bits and rejects any result ≥n, drawing again (rejection sampling, which keeps every value exactly equally likely). That spends more bits than the information. Measured, by counting the bits shuffle asks for:

Python
import math, random
class Counting(random.Random):
    """A Random that counts how many random bits shuffle() asks for."""
    used = 0
    def getrandbits(self, k):
        Counting.used += k
        return super().getrandbits(k)
rng = Counting(2026)
trials = 10_000
for _ in range(trials):
    rng.shuffle(list(range(52)))
print(f"bits drawn per 52-card shuffle: {Counting.used / trials:.1f} (information in a shuffle: {math.log2(math.factorial(52)):.1f})")
for n in (5, 8, 9, 16, 52):
    k = n.bit_length()
    print(f"randbelow({n:>2}): draws {k} bits, keeps the result with probability {n}/{2 ** k} = {n / 2 ** k:.3f},"
          f" so {k * 2 ** k / n:.2f} bits on average for {math.log2(n):.2f} bits of information")
Text
bits drawn per 52-card shuffle: 380.1 (information in a shuffle: 225.6)
randbelow( 5): draws 3 bits, keeps the result with probability 5/8 = 0.625, so 4.80 bits on average for 2.32 bits of information
randbelow( 8): draws 4 bits, keeps the result with probability 8/16 = 0.500, so 8.00 bits on average for 3.00 bits of information
randbelow( 9): draws 4 bits, keeps the result with probability 9/16 = 0.562, so 7.11 bits on average for 3.17 bits of information
randbelow(16): draws 5 bits, keeps the result with probability 16/32 = 0.500, so 10.00 bits on average for 4.00 bits of information
randbelow(52): draws 6 bits, keeps the result with probability 52/64 = 0.812, so 7.38 bits on average for 5.70 bits of information

A 52-card shuffle draws about 380 random bits for 225.6 bits of information. Two effects add up. Rounding: a choice among 5 draws 3 bits for 2.32 bits of information, and retries when the 3 bits land on 5, 6 or 7. And n.bit_length() rather than (n - 1).bit_length(): for a power of two such as 8, it draws 4 bits where 3 would do exactly, and throws away half the draws, spending 8 bits on average for 3 bits of information. The waste costs a little speed and nothing in fairness, and changing it would change the shuffles a given seed produces, which people rely on to reproduce results.

Read it yourself

Using the code above: how many random bits does randbelow(1000) draw on average, and why? Suggest a way to make a fair choice among 1000 that wastes fewer bits, using chapter 2's blocks.

Debugging drills

D1. One code short at 2⁶⁰

An id allocator sizes its fixed-length codes with bits_needed, and starts producing duplicate codes once the number of ids passes 260.

Python
import math
def bits_needed(n):
    """Binary digits a fixed-length code needs for n symbols."""
    return math.ceil(math.log2(n))
for n in (1000, 2 ** 20, 2 ** 60 + 1):
    print(f"n = {n}: {bits_needed(n)} binary digits; codes available: {2 ** bits_needed(n) >= n}")
Text
n = 1000: 10 binary digits; codes available: True
n = 1048576: 20 binary digits; codes available: True
n = 1152921504606846977: 60 binary digits; codes available: False

D2. A combination too big for a float

A report computes how many bits identify a choice of 1000 items from 2000, and crashes.

Python
import math
def bits_in_choice(n, r):
    return math.log2(math.factorial(n) / (math.factorial(r) * math.factorial(n - r)))
print(bits_in_choice(52, 5))
try:
    print(bits_in_choice(2000, 1000))
except OverflowError as e:
    print("OverflowError:", e)
Text
21.309502999115157
OverflowError: integer division result too large for a float

D3. Leading zeros that vanish

A decimal packer (the exercises' P3, without its fix) loses digits on some inputs.

Python
def encode(digits):
    return "".join(format(int(digits[i:i + 3]), "010b") for i in range(0, len(digits), 3))
def decode(bits):
    return "".join(str(int(bits[i:i + 10], 2)) for i in range(0, len(bits), 10))
for s in ("123456789", "100200300", "007042999"):
    print(s, "->", decode(encode(s)), "ok" if decode(encode(s)) == s else "WRONG")
Text
123456789 -> 123456789 ok
100200300 -> 100200300 ok
007042999 -> 742999 WRONG

D4. A shuffle that favours some orders

A hand-written shuffle swaps each position with a random position anywhere in the list. Over 270,000 shuffles of three letters, some orders appear about 25 % more often than others.

Python
import itertools, random
from collections import Counter
random.seed(4)
def naive_shuffle(xs):
    for i in range(len(xs)):
        j = random.randrange(len(xs))          # swap with any position
        xs[i], xs[j] = xs[j], xs[i]
    return xs
counts = Counter(tuple(naive_shuffle(list("abc"))) for _ in range(270_000))
for order in itertools.permutations("abc"):
    print("".join(order), f"{counts[order]:>7,}  ({counts[order] / 270_000 * 27:.2f} out of 27)")
Text
abc  39,740  (3.97 out of 27)
acb  50,455  (5.05 out of 27)
bac  49,604  (4.96 out of 27)
bca  49,828  (4.98 out of 27)
cab  40,245  (4.02 out of 27)
cba  40,128  (4.01 out of 27)

Career-oriented

Interview prep

Mid level

Q1. Why can't a comparison-based sort be faster than O(nlogn) in the worst case? Is there any way to sort faster?

How to get there. The decision tree and log2n!; then questions with more than two answers.

Q2. How many bits do you need to store a set of r distinct integers chosen from 0 to n−1? Compare with a sorted array and a bitmap.

How to get there. A set is a choice, so log2(nr).

Senior level

Q3. You're asked to generate fair random numbers from 1 to 6 from a source of random bits for a high-volume simulation. How do you make them fair, and how many bits does each cost?

How to get there. Rejection sampling, its cost, and blocks.

Q4. A team stores an event's type, region and priority as three separate one-byte columns. What could they save by packing them, and what would they lose?

How to get there. Count the combinations, compare with 24 bits.

Staff level

Q5. A product needs a short, human-friendly code (for example on a printed receipt) that identifies one of up to 100 million transactions over 5 years, and can't be guessed. How do you design its alphabet and length?

How to get there. Information to name, information to resist guessing, and human errors.

Q6. An engineer claims a new comparison-based priority queue does both insert and remove-minimum in constant time. Without reading the code, how do you evaluate the claim?

How to get there. Use the priority queue to sort.