Mini Project: A Text Search Tool That Counts Comparisons
The string-matching lessons met four algorithms that answer the same question in very different ways. In this project you put them side by side in one small search tool: it finds every occurrence of a pattern in a text with the naive algorithm, Rabin-Karp, the string-matching automaton and KMP, checks that all four agree, and reports what each one spent: character comparisons, hash updates, table lookups and preprocessing. Run on ordinary text, on DNA-like text and on an adversarial input, the counts show exactly the trade-offs the lessons proved.
Each step is a complete program; later steps repeat the pieces they need, so you can run any of them on its own.
Step 1: A cost counter and the naive matcher
Every algorithm receives a Cost object and charges it for its work under named headings. Character comparisons are the common currency; other kinds of work get their own headings, so nothing is hidden. The naive matcher only compares characters.
from collections import Counter
class Cost(Counter):
def charge(self, kind, amount=1):
self[kind] += amount
def naive(T, P, cost):
n, m, found = len(T), len(P), []
for s in range(n - m + 1):
j = 0
while j < m:
cost.charge("char comparisons")
if T[s + j] != P[j]:
break
j += 1
if j == m:
found.append(s)
return found
T = "the cat sat on the mat, then the cat ran"
for P in ["the", "cat", "at", "dog"]:
cost = Cost()
print(f"{P!r:6} found at {naive(T, P, cost)}, {dict(cost)}")'the' found at [0, 15, 24, 29], {'char comparisons': 50}
'cat' found at [4, 33], {'char comparisons': 42}
'at' found at [5, 9, 20, 34], {'char comparisons': 44}
'dog' found at [], {'char comparisons': 38}
Step 2: Rabin-Karp
Rabin-Karp is charged for the rolling-hash updates (one per shift, plus for each of the two initial hashes) and for the character comparisons spent verifying hits. It works over bytes with base 256 and the prime ; a second run with the tiny modulus shows how spurious hits inflate the comparison count.
from collections import Counter
class Cost(Counter):
def charge(self, kind, amount=1):
self[kind] += amount
def rabin_karp(T, P, cost, d=256, q=1_000_003):
n, m, found = len(T), len(P), []
if m > n:
return found
h = pow(d, m - 1, q)
p = t = 0
for i in range(m):
p = (d * p + ord(P[i])) % q
t = (d * t + ord(T[i])) % q
cost.charge("hash updates", 2 * m)
for s in range(n - m + 1):
if p == t:
cost.charge("hash hits")
j = 0
while j < m:
cost.charge("char comparisons")
if T[s + j] != P[j]:
break
j += 1
if j == m:
found.append(s)
if s < n - m:
t = (d * (t - ord(T[s]) * h) + ord(T[s + m])) % q
cost.charge("hash updates")
return found
T = "the cat sat on the mat, then the cat ran"
for q in [1_000_003, 7]:
cost = Cost()
found = rabin_karp(T, "the", cost, q=q)
print(f"q = {q:9}: found {found}, {dict(cost)}")q = 1000003: found [0, 15, 24, 29], {'hash updates': 43, 'hash hits': 4, 'char comparisons': 12}
q = 7: found [0, 15, 24, 29], {'hash updates': 43, 'hash hits': 7, 'char comparisons': 15}
With the large modulus the only hits are the four real matches. With about one window in 7 collides by accident; here three spurious hits cost extra character comparisons.
Step 3: The automaton
The automaton matcher has two phases with very different costs. Building the transition table with the fast construction of String Matching with Finite Automata fills entries; matching then costs exactly one table lookup per text character and no comparisons at all. The alphabet is taken from the text and the pattern.
from collections import Counter
class Cost(Counter):
def charge(self, kind, amount=1):
self[kind] += amount
def automaton(T, P, cost):
alphabet = sorted(set(T) | set(P))
m = len(P)
delta = [{a: 0 for a in alphabet} for _ in range(m + 1)]
delta[0][P[0]] = 1
x = 0
for q in range(1, m + 1):
for a in alphabet:
delta[q][a] = delta[x][a]
if q < m:
delta[q][P[q]] = q + 1
x = delta[x][P[q]]
cost.charge("table entries built", (m + 1) * len(alphabet))
q, found = 0, []
for i, c in enumerate(T):
q = delta[q][c]
cost.charge("table lookups")
if q == m:
found.append(i - m + 1)
return found
T = "the cat sat on the mat, then the cat ran"
for P in ["the", "at", "cat ran"]:
cost = Cost()
print(f"{P!r:10} found at {automaton(T, P, cost)}, {dict(cost)}")'the' found at [0, 15, 24, 29], {'table entries built': 48, 'table lookups': 40}
'at' found at [5, 9, 20, 34], {'table entries built': 36, 'table lookups': 40}
'cat ran' found at [33], {'table entries built': 96, 'table lookups': 40}
Step 4: KMP
KMP is charged for the character comparisons of both phases, the prefix function and the scan, kept under separate headings so that the and bounds of The Knuth-Morris-Pratt Algorithm can be checked directly.
from collections import Counter
class Cost(Counter):
def charge(self, kind, amount=1):
self[kind] += amount
def kmp(T, P, cost):
m = len(P)
pi, k = [0] * m, 0
for q in range(1, m):
while True: # one comparison per try: fallbacks + 1
cost.charge("prefix comparisons")
if P[k] == P[q]:
k += 1
break
if k == 0:
break
k = pi[k - 1]
pi[q] = k
q, found = 0, []
for i, c in enumerate(T):
while True:
cost.charge("char comparisons")
if P[q] == c:
q += 1
break
if q == 0:
break
q = pi[q - 1]
if q == m:
found.append(i - m + 1)
q = pi[q - 1]
return found
T = "the cat sat on the mat, then the cat ran"
for P in ["the", "at", "abab"]:
cost = Cost()
found = kmp(T, P, cost)
print(f"{P!r:7} found at {found}, {dict(cost)}, bounds 2m = {2 * len(P)}, 2n = {2 * len(T)}")'the' found at [0, 15, 24, 29], {'prefix comparisons': 2, 'char comparisons': 44}, bounds 2m = 6, 2n = 80
'at' found at [5, 9, 20, 34], {'prefix comparisons': 1, 'char comparisons': 41}, bounds 2m = 4, 2n = 80
'abab' found at [], {'prefix comparisons': 3, 'char comparisons': 45}, bounds 2m = 8, 2n = 80
Each text character costs one comparison plus one per fallback, and the fallbacks number at most in total, so the scan never exceeds comparisons; the same argument bounds the prefix function by .
Step 5: The comparison
The final tool runs all four algorithms on three kinds of input, checks that they report the same shifts and prints one table: an English text with a common word, a random DNA string with a pattern taken from it, and the adversarial input , that drives the naive algorithm to its worst case.
import random
from collections import Counter
class Cost(Counter):
def charge(self, kind, amount=1):
self[kind] += amount
def naive(T, P, cost):
n, m, found = len(T), len(P), []
for s in range(n - m + 1):
j = 0
while j < m:
cost.charge("comparisons")
if T[s + j] != P[j]:
break
j += 1
if j == m:
found.append(s)
return found
def rabin_karp(T, P, cost, d=256, q=1_000_003):
n, m, found = len(T), len(P), []
h, p, t = pow(d, m - 1, q), 0, 0
for i in range(m):
p, t = (d * p + ord(P[i])) % q, (d * t + ord(T[i])) % q
cost.charge("other work", 2 * m)
for s in range(n - m + 1):
if p == t:
j = 0
while j < m:
cost.charge("comparisons")
if T[s + j] != P[j]:
break
j += 1
if j == m:
found.append(s)
if s < n - m:
t = (d * (t - ord(T[s]) * h) + ord(T[s + m])) % q
cost.charge("other work")
return found
def automaton(T, P, cost):
alphabet, m = sorted(set(T) | set(P)), len(P)
delta = [{a: 0 for a in alphabet} for _ in range(m + 1)]
delta[0][P[0]], x = 1, 0
for q in range(1, m + 1):
for a in alphabet:
delta[q][a] = delta[x][a]
if q < m:
delta[q][P[q]] = q + 1
x = delta[x][P[q]]
cost.charge("other work", (m + 1) * len(alphabet))
q, found = 0, []
for i, c in enumerate(T):
q = delta[q][c]
cost.charge("other work")
if q == m:
found.append(i - m + 1)
return found
def kmp(T, P, cost):
m, pi, k = len(P), [0] * len(P), 0
for q in range(1, m):
while True:
cost.charge("comparisons")
if P[k] == P[q]:
k += 1
break
if k == 0:
break
k = pi[k - 1]
pi[q] = k
q, found = 0, []
for i, c in enumerate(T):
while True:
cost.charge("comparisons")
if P[q] == c:
q += 1
break
if q == 0:
break
q = pi[q - 1]
if q == m:
found.append(i - m + 1)
q = pi[q - 1]
return found
rng = random.Random(2026)
words = "the of and to in is was that for it as with be on not this but by at from".split()
english = " ".join(rng.choice(words) for _ in range(2000))
dna = "".join(rng.choice("acgt") for _ in range(10000))
inputs = [("English, 'that'", english, "that"),
("DNA, 12 letters", dna, dna[7000:7012]),
("a^n vs a^99 b", "a" * 5000, "a" * 99 + "b")]
print(f"{'input':17} {'n':>6} {'matches':>8} {'algorithm':12} {'comparisons':>12} {'other work':>11}")
for label, T, P in inputs:
results = {}
for name, alg in [("naive", naive), ("Rabin-Karp", rabin_karp), ("automaton", automaton), ("KMP", kmp)]:
cost = Cost()
results[name] = (alg(T, P, cost), cost)
shifts = {tuple(r[0]) for r in results.values()}
assert len(shifts) == 1, "the algorithms disagree"
for i, (name, (found, cost)) in enumerate(results.items()):
head = f"{label:17} {len(T):6} {len(found):8}" if i == 0 else " " * 33
print(f"{head} {name:12} {cost['comparisons']:12} {cost['other work']:11}")input n matches algorithm comparisons other work
English, 'that' 7371 82 naive 8808 0
Rabin-Karp 328 7375
automaton 0 7456
KMP 8263 0
DNA, 12 letters 10000 1 naive 13322 0
Rabin-Karp 12 10012
automaton 0 10052
KMP 12517 0
a^n vs a^99 b 5000 0 naive 490100 0
Rabin-Karp 0 5100
automaton 0 5202
KMP 10098 0
Reading the table
- English text. The naive algorithm makes little more than one comparison per position: most windows fail on the first letter. Rabin-Karp compares characters only at the real matches, but pays one hash update per position. KMP makes slightly more comparisons than characters. The automaton never compares; its "other work" is one lookup per character plus the table.
- DNA. With four letters, a window survives the first comparison a quarter of the time, so the naive count rises to about per position, matching the random-text bound of The Naive String-Matching Algorithm.
- Adversarial input. Here the naive algorithm makes comparisons, almost half a million, while KMP stays below (its scan plus the prefix function; the table counts both) and the automaton does exactly lookups after building its table. Rabin-Karp has no hits at all (the pattern contains a
b), so it is linear too; its own worst case would be a text full of real matches, such as searching for in .
Extensions
- Add the input , and watch Rabin-Karp's comparison count jump: every shift is a valid match.
- Report the matches with their line numbers and some context, like
grep, and read the text from a multi-line string. - Add a fifth algorithm, Boyer-Moore-Horspool, which compares the window from its right end and skips ahead by a table of last occurrences. On English text it reads only a fraction of the characters.
- Build a suffix array of the text once (Suffix Arrays: An Introduction) and answer many pattern queries with binary search; count the character comparisons per query and compare with running KMP for each.
- Port the tool to C++ with the
std::boyer_moore_searcherfrom<functional>as a reference, and check that every algorithm reports the same shifts on large random inputs.
Test yourself
On the adversarial input , , which algorithm makes about character comparisons?
- KMP
- The automaton
- The naive algorithm
- Rabin-Karp with a large prime
Which input makes Rabin-Karp check many windows character by character, even with a large prime modulus?
- Random text
- A text where the pattern occurs at almost every shift, such as in
- A text with no occurrences
- A very short pattern in English text
Why does the automaton matcher report no character comparisons in the table?
- Because it is wrong
- Because each text character only selects the next state from the precomputed table
- Because it uses hashing
- Because it skips characters