---
title: "Searching in Text"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 29
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/29-searching-in-text
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 29 — Searching in Text

A text editor finds a word in a book of a million letters before the finger leaves the key. The obvious way is to try the word at every position of the text, comparing letters until one differs. It works, and it reads every letter of the text at least once. A cleverer search looks at the word before it starts, and then, at most positions, reads one letter and jumps several places at once.

This chapter writes both searches, counts the letters they compare, and shows when the jumps are long and when they are short. The cost is measured on generated texts rather than proved: the guarantee of the cleverer method is that it never misses an [occurrence](#def-g12-text-search-pattern), and that much is proved.

**You already know.**

A string is a sequence of characters, indexed from $0$; `s[i:j]` is the slice from $i$ up to $j$ (Book 1, grade 7; chapter [5](https://one-course.com/books/computer-science/2/en/chapter/5-text-encodings-from-ascii-to-utf-8#ch-g10-text-encodings)). The cost of an algorithm is counted in elementary steps, as a function of the size of its input (chapter [17](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#ch-g11-cost-of-an-algorithm)). A dictionary maps keys to values, and `d.get(k, default)` gives a value with a default for absent keys (Book 1, grade 8).

## 29.1 The naive search

**Definition 29.1 (Pattern, occurrence).**

In text search, the *pattern* is the string looked for, of length $m$, in a *text* of length $n$. An *occurrence* of the pattern is a position $i$ of the text with `text[i:i + m] == p`. Placing the pattern under the text from position $i$ is called an *alignment*; there are $n - m + 1$ of them.

The naive search tries every alignment, from left to right. At each one it compares the letters of the [pattern](#def-g12-text-search-pattern) with those of the text above them, from the first, and gives up at the first difference.

```python
"""The naive search: try the pattern at every position of the text."""


def search_naive(text, p):
    """Return the positions where p occurs in text, and the comparisons made."""
    n, m = len(text), len(p)
    positions, comparisons = [], 0
    for i in range(n - m + 1):              # every alignment of p under text
        j = 0
        while j < m:
            comparisons += 1
            if text[i + j] != p[j]:
                break                       # mismatch: give up this alignment
            j += 1
        if j == m:
            positions.append(i)
    return positions, comparisons


if __name__ == "__main__":
    text = "a man a plan a canal panama"
    print(search_naive(text, "an"))
    print(search_naive(text, "canal"))
    print(search_naive(text, "pan"), search_naive(text, "boat"))
```

***Listing 29.1.** The naive search, with its comparisons counted. code/grade-12/08-text-search/listings/naive.py*

```
$ python naive.py
([3, 10, 16, 22], 35)
([15], 27)
([21], 28) ([], 24)
```

***Output 29.1.** Positions found, and comparisons made, in a text of $27$ letters.*

![The naive search for plan. Each row is one alignment; the boxed letter is the one compared, the grey letters are never looked at. In ordinary text most alignments fail at the first or second letter, so the search makes a little more than one comparison per position.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-text-search/fig-2f2d264702a9.svg)

*The naive search for `plan`. Each row is one alignment; the boxed letter is the one compared, the grey letters are never looked at. In ordinary text most alignments fail at the first or second letter, so the search makes a little more than one comparison per position.*

In the worst case, every alignment matches all letters but the last. In a text of $n$ letters `a`, the [pattern](#def-g12-text-search-pattern) `aa...ab` costs $m$ comparisons at each of the $n - m + 1$ alignments.

```python
from naive import search_naive

n = 1000
text = "a" * n
for m in [2, 5, 10, 50, 100]:
    p = "a" * (m - 1) + "b"                 # matches m - 1 letters, then fails
    positions, comparisons = search_naive(text, p)
    print(f"m = {m:3}: {comparisons:6} comparisons = (n - m + 1) * m =",
          (n - m + 1) * m)
```

***Listing 29.2.** The worst case of the naive search. code/grade-12/08-text-search/listings/worst_naive.py*

```
$ python worst_naive.py
m =   2:   1998 comparisons = (n - m + 1) * m = 1998
m =   5:   4980 comparisons = (n - m + 1) * m = 4980
m =  10:   9910 comparisons = (n - m + 1) * m = 9910
m =  50:  47550 comparisons = (n - m + 1) * m = 47550
m = 100:  90100 comparisons = (n - m + 1) * m = 90100
```

***Output 29.2.** Exactly $(n - m + 1) \times m$ comparisons.*

## 29.2 Looking at the pattern first

Suppose the [pattern](#def-g12-text-search-pattern) is `STATION` and, at some alignment, the text letter under its last place is a `K`. No letter of `STATION` is a `K`. Any alignment that puts a letter of the [pattern](#def-g12-text-search-pattern) under that `K` fails; the [pattern](#def-g12-text-search-pattern) can jump past it, seven places at once. If the letter were a `T`, the [pattern](#def-g12-text-search-pattern) could jump until its own last `T`, not counting the final place, comes under it: three places.

These distances depend on the [pattern](#def-g12-text-search-pattern) only, so they can be computed once, before reading the text. Doing work on the [pattern](#def-g12-text-search-pattern) in advance to save work on the text is called *preprocessing*.

**Definition 29.2 (Shift table).**

The *shift table* of a [pattern](#def-g12-text-search-pattern) $p$ of length $m$ gives, for each letter $c$, the distance from the last place of $c$ in $p$, the final place excluded, to the final place: $m - 1 - j$, where $j$ is that last place. A letter absent from the first $m - 1$ places of $p$ gets the shift $m$.

```python
"""Horspool's shift table: how far may the pattern jump?"""


def shift_table(p):
    """For each letter of p but the last: distance from its last place to the end."""
    m = len(p)
    shift = {}
    for j in range(m - 1):                  # the last letter of p is left out
        shift[p[j]] = m - 1 - j             # later places overwrite earlier ones
    return shift


if __name__ == "__main__":
    for p in ["STATION", "TOWN", "ABAB"]:
        print(p, shift_table(p), "| any other letter:", len(p))
```

***Listing 29.3.** The [shift table](#def-g12-text-search-shift-table), as a dictionary; absent letters are left out. code/grade-12/08-text-search/listings/shift_table.py*

```
$ python shift_table.py
STATION {'S': 6, 'T': 3, 'A': 4, 'I': 2, 'O': 1} | any other letter: 7
TOWN {'T': 3, 'O': 2, 'W': 1} | any other letter: 4
ABAB {'A': 1, 'B': 2} | any other letter: 4
```

***Output 29.3.** The later `T` of `STATION` overwrote the earlier one.*

![The shift table of STATION (m = 7). The last T before the final place is at 3, three places from the end: shift 3. N, which appears only in the final place (shaded), and every letter absent from the pattern get 7.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-text-search/fig-8b947f89afc1.svg)

*The [shift table](#def-g12-text-search-shift-table) of `STATION` ($m = 7$). The last `T` before the final place is at $3$, three places from the end: shift $3$. `N`, which appears only in the final place (shaded), and every letter absent from the [pattern](#def-g12-text-search-pattern) get $7$.*

## 29.3 The Boyer–Moore–Horspool search

**Method 29.3 (Boyer–Moore–Horspool).**

The *Boyer–Moore–Horspool algorithm* computes the [shift table](#def-g12-text-search-shift-table) of the [pattern](#def-g12-text-search-pattern), then places the [pattern](#def-g12-text-search-pattern) at position $i = 0$ and repeats while $i \le n - m$: compare the [pattern](#def-g12-text-search-pattern) with the text above it from right to left, and record $i$ if all $m$ letters agree; then, whatever happened, read the text letter $c$ under the [pattern](#def-g12-text-search-pattern)’s last place and move the [pattern](#def-g12-text-search-pattern) $\mathrm{shift}(c)$ places to the right.

```python
"""The Boyer-Moore-Horspool search."""
from shift_table import shift_table


def horspool(text, p, trace=False):
    n, m = len(text), len(p)
    shift = shift_table(p)
    positions, comparisons, i = [], 0, 0
    while i <= n - m:                       # p is under text[i:i + m]
        j = m - 1
        while j >= 0:                       # compare from the right
            comparisons += 1
            if text[i + j] != p[j]:
                break
            j -= 1
        if j < 0:
            positions.append(i)
        last = text[i + m - 1]              # the text letter under p's last place
        if trace:
            print(f"{' ' * i}{p}   at {i:2}: {'found' if j < 0 else 'no'},"
                  f" '{last}' -> jump {shift.get(last, m)}")
        i += shift.get(last, m)
    return positions, comparisons


if __name__ == "__main__":
    text = "the bus to the station stops at the town hall"
    print(text)
    print(horspool(text, "station", trace=True))
    print(horspool(text, "the"))
```

***Listing 29.4.** Horspool’s search, with a trace of the alignments. code/grade-12/08-text-search/listings/horspool.py*

```
$ python horspool.py
the bus to the station stops at the town hall
station   at  0: no, 's' -> jump 6
      station   at  6: no, 'h' -> jump 7
             station   at 13: no, 'i' -> jump 2
               station   at 15: found, 'n' -> jump 7
                      station   at 22: no, ' ' -> jump 7
                             station   at 29: no, ' ' -> jump 7
                                    station   at 36: no, 'a' -> jump 4
([15], 13)
([0, 11, 32], 22)
```

***Output 29.4.** Seven alignments and $13$ comparisons to find `station` in $45$ letters; then `the`, three times.*

![A jump of Horspool’s search for station. At position 0, the first step of the trace, the text letter under the last place is s; the pattern’s only s is 6 places from its end, so the pattern jumps 6 places, bringing its s under the text’s s. Any smaller jump would put some other letter of the pattern under that s.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-text-search/fig-8f273e205cfd.svg)

*A jump of Horspool’s search for `station`. At position $0$, the first step of the trace, the text letter under the last place is `s`; the [pattern](#def-g12-text-search-pattern)’s only `s` is $6$ places from its end, so the [pattern](#def-g12-text-search-pattern) jumps $6$ places, bringing its `s` under the text’s `s`. Any smaller jump would put some other letter of the [pattern](#def-g12-text-search-pattern) under that `s`.*

Why are no [occurrences](#def-g12-text-search-pattern) skipped? Let $c$ be the text letter under the last place, at alignment $i$, and $s$ its shift. For a jump of $d$ places with $1 \le d < s$, the letter of the [pattern](#def-g12-text-search-pattern) that would come under $c$ is at place $m - 1 - d$, which is not the last place and lies after the last place of $c$ among the first $m - 1$; so it is not $c$, and that alignment fails. The alignments jumped over all fail, and the search tries every one that could succeed (exercise [29.12](#exo-g12-text-search-12)).

**History — Boyer and Moore, 1977; Horspool, 1980.**

Robert S. Boyer and J Strother Moore published “A fast string searching algorithm” in the *Communications of the ACM* in 1977; their method uses the [shift table](#def-g12-text-search-shift-table) of this chapter and a second, more elaborate table. In 1980, R. Nigel Horspool showed in “Practical fast searching in strings” that the first table alone gives most of the speed.

## 29.4 The cost in practice

How many comparisons does each search make for each letter of the text? The answer depends on the text. The program draws random texts of $100\,000$ letters, from $26$ letters and from four (`A`, `C`, `G`, `T`, as in genetic sequences), and cuts the [patterns](#def-g12-text-search-pattern) from the texts so that each occurs at least once.

```python
"""Comparisons per text letter, naive and Horspool, on generated texts."""
import random

from horspool import horspool
from naive import search_naive

rng = random.Random(8)
n = 100_000
alphabets = [("26 letters", "abcdefghijklmnopqrstuvwxyz"), ("4 letters", "ACGT")]
for name, alphabet in alphabets:
    text = "".join(rng.choice(alphabet) for _ in range(n))
    for m in [4, 8, 16, 32]:
        start = rng.randrange(n - m)
        p = text[start:start + m]           # a pattern that occurs at least once
        found_n, naive_c = search_naive(text, p)
        found_h, hors_c = horspool(text, p)
        assert found_n == found_h
        print(f"{name}, m = {m:2}: naive {naive_c / n:5.2f} per letter,"
              f" Horspool {hors_c / n:5.2f}, found {len(found_h)}")
```

***Listing 29.5.** Comparisons per text letter on generated texts. code/grade-12/08-text-search/listings/compare_counts.py*

```
$ python compare_counts.py
26 letters, m =  4: naive  1.04 per letter, Horspool  0.28, found 1
26 letters, m =  8: naive  1.04 per letter, Horspool  0.15, found 1
26 letters, m = 16: naive  1.04 per letter, Horspool  0.09, found 1
26 letters, m = 32: naive  1.04 per letter, Horspool  0.05, found 1
4 letters, m =  4: naive  1.33 per letter, Horspool  0.47, found 378
4 letters, m =  8: naive  1.33 per letter, Horspool  0.31, found 5
4 letters, m = 16: naive  1.33 per letter, Horspool  0.47, found 1
4 letters, m = 32: naive  1.33 per letter, Horspool  0.35, found 1
```

***Output 29.5.** With $26$ letters, Horspool’s count falls as the [pattern](#def-g12-text-search-pattern) grows; with four, it does not go on falling.*

![Comparisons per text letter, averaged over five patterns for each length, on random texts of 50\,000 letters, from figures/per_letter.py. The naive search stays near 1.04 and 1.33 whatever the pattern. With 26 letters Horspool’s count falls roughly like 1/m, to 0.06 at m = 32; with four letters it stays around 0.4.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-text-search/fig-ddc76a13049b.svg)

*Comparisons per text letter, averaged over five [patterns](#def-g12-text-search-pattern) for each length, on random texts of $50\,000$ letters, from `figures/per_letter.py`. The naive search stays near $1.04$ and $1.33$ whatever the [pattern](#def-g12-text-search-pattern). With $26$ letters Horspool’s count falls roughly like $1/m$, to $0.06$ at $m = 32$; with four letters it stays around $0.4$.*

The jump is long only when the letter under the last place is rare in the [pattern](#def-g12-text-search-pattern). With $26$ letters, most text letters do not appear in a short [pattern](#def-g12-text-search-pattern) at all, and the [pattern](#def-g12-text-search-pattern) jumps its whole length. With four letters, every letter appears among the last few places of any long [pattern](#def-g12-text-search-pattern), so the jumps stay short, about four places, however long the [pattern](#def-g12-text-search-pattern). The worst case is as bad as the naive search’s: in a text of `a`s, the [pattern](#def-g12-text-search-pattern) `baa...a` costs $m$ comparisons at each alignment and jumps one place (exercise [29.13](#exo-g12-text-search-13)).

On the titles of the town library, joined into one text, the counts are those of ordinary text.

```python
"""Searching the titles of the town library, joined into one text."""
import csv

from horspool import horspool
from naive import search_naive

with open("books.csv", newline="") as f:
    titles = [row["title"] for row in csv.DictReader(f)]
text = "\n".join(titles)                    # one title per line
print(len(titles), "titles,", len(text), "letters")
for word in ["Forest", "River", "The", "Lighthouse", "Silent Code"]:
    found, naive_c = search_naive(text, word)
    found_h, hors_c = horspool(text, word)
    lines = [text.count("\n", 0, i) + 1 for i in found_h]
    shown = lines if len(lines) <= 8 else lines[:3] + ["..."]
    print(f"{word!r:14} {len(lines):2} found  naive {naive_c:5}  Horspool {hors_c:4}"
          f"  lines {shown}")
```

***Listing 29.6.** Five words searched in the library’s titles. code/grade-12/08-text-search/listings/town_titles.py*

```
$ python town_titles.py
80 titles, 1437 letters
'Forest'        8 found  naive  1472  Horspool  324  lines [2, 9, 12, 21, 33, 54, 69, 73]
'River'         2 found  naive  1441  Horspool  361  lines [34, 80]
'The'          42 found  naive  1523  Horspool  672  lines [1, 2, 7, '...']
'Lighthouse'    4 found  naive  1488  Horspool  225  lines [5, 44, 50, 66]
'Silent Code'   1 found  naive  1489  Horspool  256  lines [1]
```

***Output 29.6.** The longer the word, the fewer letters Horspool reads; for `The`, three letters long, it still saves half.*

## 29.5 Searching in practice

Counting comparisons is not the same as timing. A Python loop costs far more per step than the machine code of the interpreter’s own string methods.

```python
"""Naive search, Horspool and str.find, timed on a million random letters."""
import random
import time

from horspool import horspool
from naive import search_naive


def all_find(text, p):
    positions, i = [], text.find(p)
    while i != -1:
        positions.append(i)
        i = text.find(p, i + 1)
    return positions


def seconds(f, *args):
    start = time.perf_counter()
    result = f(*args)
    return time.perf_counter() - start, result


rng = random.Random(3)
text = "".join(rng.choice("abcdefghijklmnopqrstuvwxyz ") for _ in range(1_000_000))
for p in ["town", "station square"]:
    t_naive, (found, _) = seconds(search_naive, text, p)
    t_hors, (found_h, _) = seconds(horspool, text, p)
    t_find, found_f = seconds(all_find, text, p)
    assert found == found_h == found_f
    print(f"{p!r:16} found {len(found)}:  naive {t_naive:5.2f} s   Horspool"
          f" {t_hors:5.2f} s   str.find {t_find * 1000:6.2f} ms")
```

***Listing 29.7.** The two searches and `str.find`, timed on a million letters. code/grade-12/08-text-search/listings/measure_find.py*

```
$ python measure_find.py
'town'           found 1:  naive  0.05 s   Horspool  0.03 s   str.find   0.52 ms
'station square' found 0:  naive  0.05 s   Horspool  0.01 s   str.find   0.32 ms
```

***Output 29.7.** On the author’s laptop. `str.find` answers in under a millisecond, many times faster than either Python loop.*

**In practice — Searching in real programs.**

Python’s `str.find`, `in` and `str.count` are written in C and use a search of the Boyer–Moore family, with a [shift table](#def-g12-text-search-shift-table) of their own. Text editors and command-line tools search the same way. Searching for many words at once, such as every name of a list in a long text, uses a different preprocessing: the words are merged into one structure that is followed letter by letter through the text, reading each letter once. It is studied in Book 4.

## 29.6 Exercises

**Exercise 29.1 ★.**

Where does `ana` occur in `bananas`? Do the [occurrences](#def-g12-text-search-pattern) overlap?

**Solution of Exercise 29.1.**

At positions $1$ and $3$: `b[ana]nas` and `ban[ana]s`. They overlap: the `a` at position $3$ belongs to both.

**Exercise 29.2 ★.**

Count the comparisons of `search_naive("abcabd", "abd")`.

**Solution of Exercise 29.2.**

Position $0$: `a`, `b` agree, `c` differs from `d`: $3$. Positions $1$ and $2$: one each. Position $3$: `a`, `b`, `d` agree: $3$, found. In all $8$ comparisons, and the [occurrence](#def-g12-text-search-pattern) $[3]$.

**Exercise 29.3 ★.**

Write the [shift table](#def-g12-text-search-shift-table) of `BANANA`.

**Solution of Exercise 29.3.**

The first five places are `BANAN`. `B` is last at $0$: $5$. `A` is last at $3$: $2$. `N` is last at $4$: $1$. Every other letter: $6$.

**Exercise 29.4 ★.**

List the alignments Horspool’s search tries for `TOWN` in `THE OLD TOWN HALL`, and the jump after each.

**Solution of Exercise 29.4.**

The table of `TOWN`: `T` $3$, `O` $2$, `W` $1$, others $4$. Position $0$: the space under the last place, no match, jump $4$. Position $4$: under the last place, the space after `OLD`, jump $4$. Position $8$: `TOWN`, found; under the last place an `N`, jump $4$. Position $12$: an `L`, jump $4$, and $16 > 17 - 4$ ends the search. Four alignments.

**Exercise 29.5 ★.**

Write `count_occurrences(text, p)` with slices, trying every position.

**Solution of Exercise 29.5.**

    `def count_occurrences(text, p):`

        `count = 0`

        `for i in range(len(text) - len(p) + 1):`

            `if text[i:i + len(p)] == p:`

                `count += 1`

        `return count`

The slice comparison hides the letter-by-letter loop of `search_naive`; the cost is the same.

**Exercise 29.6 ★★.**

A student writes `for i in range(len(text) - len(p))`. Which [occurrences](#def-g12-text-search-pattern) are missed? Give the smallest test that catches it.

**Solution of Exercise 29.6.**

The last alignment, $i = n - m$, is never tried: an [occurrence](#def-g12-text-search-pattern) at the very end of the text is missed. The smallest test is a text equal to the [pattern](#def-g12-text-search-pattern), such as `search("a", "a")`, which must find $[0]$; `"the town"` with `"town"` also catches it.

**Exercise 29.7 ★★.**

Write `horspool_first(text, p)`, which returns the first [occurrence](#def-g12-text-search-pattern), or $-1$, and stops as soon as it is found.

**Solution of Exercise 29.7.**

    `def horspool_first(text, p):`

        `n, m = len(text), len(p)`

        `shift, i = shift_table(p), 0`

        `while i <= n - m:`

            `j = m - 1`

            `while j >= 0 and text[i + j] == p[j]:`

                `j -= 1`

            `if j < 0:`

                `return i`

            `i += shift.get(text[i + m - 1], m)`

        `return -1`

The tests compare it with the first position of every [occurrence](#def-g12-text-search-pattern) on $400$ random cases.

**Exercise 29.8 ★★.**

A student builds the [shift table](#def-g12-text-search-shift-table) with `range(m)` instead of `range(m - 1)`. What is the shift of `N` for `TOWN`? What happens when the search meets an `N` under the last place?

**Solution of Exercise 29.8.**

`N` is at the last place, $3$, and gets $4 - 1 - 3 = 0$. When an `N` of the text comes under the last place (for instance once `TOWN` is found), the [pattern](#def-g12-text-search-pattern) moves $0$ places: the same alignment is tried again, for ever. The last place must be left out, so that every shift is at least $1$.

**Exercise 29.9 ★★.**

For a text of $n$ letters, which [pattern](#def-g12-text-search-pattern) length $m$ makes the worst case of the naive search, $(n - m + 1)m$, the largest? How many comparisons for $n = 1000$?

**Solution of Exercise 29.9.**

$(n - m + 1)m$ is largest for $m$ near $(n + 1)/2$, the middle of its two roots $0$ and $n + 1$. For $n = 1000$: $m = 500$ or $501$, and $501 \times 500 = 250\,500$ comparisons, a quarter of $n^2$.

**Exercise 29.10 ★★.**

Where does `ABAB` occur in `ABABABAB`, by the naive search? What does `"ABABABAB".count("ABAB")` return, and why the difference?

**Solution of Exercise 29.10.**

At $0$, $2$ and $4$. `count` returns $2$: it counts [occurrences](#def-g12-text-search-pattern) that do not overlap, so after the one at $0$ it resumes at $4$. A search for every [occurrence](#def-g12-text-search-pattern) must allow overlaps; a count of separate copies must not.

**Exercise 29.11 ★★.**

Write `search_ignore_case(text, p)`, which finds `TOWN` in `The Town and the town` twice.

**Solution of Exercise 29.11.**

    `def search_ignore_case(text, p):`

        `return horspool(text.lower(), p.lower())[0]`

It returns $[4, 17]$. Lowering the case of the whole text costs one pass over it; for many searches in the same text, it is done once.

**Exercise 29.12 ★★★.**

Prove that Horspool’s search finds every [occurrence](#def-g12-text-search-pattern): no alignment it jumps over is an [occurrence](#def-g12-text-search-pattern).

**Solution of Exercise 29.12.**

Let the search be at alignment $i$, let $c$ be the text letter at $i + m - 1$, under the [pattern](#def-g12-text-search-pattern)’s last place, and $s = \mathrm{shift}(c)$. Take an alignment $i + d$ with $1 \le d < s$. Under the text letter $c$ it puts the [pattern](#def-g12-text-search-pattern)’s place $m - 1 - d$, which is between $m - s$ and $m - 2$. If $c$ appears among the first $m - 1$ places, its last place there is $m - 1 - s$, so the places from $m - s$ to $m - 2$ hold no $c$; if it does not appear, no place does. Either way the [pattern](#def-g12-text-search-pattern)’s letter under $c$ is not $c$, and alignment $i + d$ is not an [occurrence](#def-g12-text-search-pattern). So the alignments jumped over are not [occurrences](#def-g12-text-search-pattern), and every alignment not jumped over is checked letter by letter.

**Exercise 29.13 ★★★.**

Show that for the text of $n$ letters `a` and the [pattern](#def-g12-text-search-pattern) `b` followed by $m - 1$ letters `a`, Horspool’s search makes exactly $m(n - m + 1)$ comparisons.

**Solution of Exercise 29.13.**

At every alignment the window is $m$ letters `a`. Comparing from the right, the last $m - 1$ places of the [pattern](#def-g12-text-search-pattern) are `a` and agree, and the first, `b`, does not: $m$ comparisons. The letter under the last place is `a`, whose last place among the first $m - 1$ is $m - 2$: shift $1$. So every one of the $n - m + 1$ alignments is tried, at $m$ comparisons each. The tests check $m(n - m + 1)$ for three pairs $(n, m)$.

**Exercise 29.14 ★★★.**

Write `search_wildcard(text, p)`, in which a `?` of the [pattern](#def-g12-text-search-pattern) matches any one letter. Why does the [shift table](#def-g12-text-search-shift-table) not work directly with a `?`?

**Solution of Exercise 29.14.**

    `def search_wildcard(text, p):`

        `n, m = len(text), len(p)`

        `found = []`

        `for i in range(n - m + 1):`

            `if all(p[j] == "?" or p[j] == text[i + j] for j in range(m)):`

                `found.append(i)`

        `return found`

The proof of exercise [29.12](#exo-g12-text-search-12) needs that the [pattern](#def-g12-text-search-pattern)’s letter under $c$ is not $c$; a `?` matches every $c$. A `?` at place $j < m - 1$ limits every shift to at most $m - 1 - j$; the table must be built that way, or the search must stay naive. `st?` finds $15$ and $23$ in `the bus to the station stops`.

**Exercise 29.15 ★★★.**

On a random text of four letters, the mean jump of Horspool’s search stays around four places, whatever the length of the [pattern](#def-g12-text-search-pattern). Explain why, and measure the mean jump for one [pattern](#def-g12-text-search-pattern) of length $32$.

**Solution of Exercise 29.15.**

A letter’s shift is its distance from the end, counted from its last place among the first $m - 1$. In a random [pattern](#def-g12-text-search-pattern) each place holds a given letter with chance $\frac14$, so the last place of that letter is usually within the last few places: places $m - 2$, $m - 3$, … each miss it with chance $\frac34$. The shifts are about $1$ to $8$ whatever $m$, and their mean about $4$. For one [pattern](#def-g12-text-search-pattern) of length $32$ cut from a random text of $200\,000$ letters, the [shift table](#def-g12-text-search-shift-table) was `C` $3$, `G` $1$, `T` $5$, `A` $4$, mean $3.25$; over the $61\,343$ jumps of the search, the measured mean was $3.26$.

## 29.7 Problem: Searching a Long Chain of Letters

**Problem 29.1.**

Weekend problem — a million letters, four of them

A genetic sequence is written with four letters, `A`, `C`, `G`, `T`. The program draws a random chain of a million of them, cuts five [patterns](#def-g12-text-search-pattern) of each length from it, and runs both searches.

```python
"""A million letters from A, C, G, T: how much of it does each search read?"""
import random

from horspool import horspool
from naive import search_naive
from shift_table import shift_table

rng = random.Random(2026)
n = 1_000_000
text = "".join(rng.choice("ACGT") for _ in range(n))
print("first letters:", text[:40])
for m in [4, 8, 16, 32]:
    naive_total = hors_total = jump_total = 0
    for _ in range(5):                       # five patterns cut from the text
        start = rng.randrange(n - m)
        p = text[start:start + m]
        found, naive_c = search_naive(text, p)
        found_h, hors_c = horspool(text, p)
        assert found == found_h
        naive_total += naive_c
        hors_total += hors_c
        table = shift_table(p)
        jump_total += sum(table.get(c, m) for c in "ACGT") / 4
    print(f"m = {m:2}: naive {naive_total / 5 / n:.3f} per letter,"
          f" Horspool {hors_total / 5 / n:.3f}, ratio {naive_total / hors_total:.1f},"
          f" mean jump {jump_total / 5:.2f}")
```

***Listing 29.8.** Both searches on a million letters of four kinds. code/grade-12/08-text-search/listings/chain.py*

```
$ python chain.py
first letters: AGACTTTCAAAGATATGCTGGGTAGAGGTCGAGGTTATTA
m =  4: naive 1.328 per letter, Horspool 0.514, ratio 2.6, mean jump 2.75
m =  8: naive 1.333 per letter, Horspool 0.412, ratio 3.2, mean jump 3.60
m = 16: naive 1.334 per letter, Horspool 0.363, ratio 3.7, mean jump 4.25
m = 32: naive 1.334 per letter, Horspool 0.398, ratio 3.4, mean jump 3.80
```

***Output 29.8.** Comparisons per letter, their ratio, and the mean jump of the [shift tables](#def-g12-text-search-shift-table).*

**Part I — The chain.**

1. Why are the [patterns](#def-g12-text-search-pattern) cut from the text rather than drawn at random?
2. In a random chain, how often would you expect a given [pattern](#def-g12-text-search-pattern) of $4$ letters? Compare with the $378$ found in the $100\,000$ letters of `compare_counts.py` .
3. Why is a [pattern](#def-g12-text-search-pattern) of $16$ letters very unlikely to occur twice?
4. What does `assert found == found_h` check, and why is it in the program?

**Part II — The naive search.**

5. At an alignment, what is the chance that the first comparison fails? That the search reaches a second comparison? A third?
6. Explain why the naive search makes about $1 + \frac14 + \frac1{16} + \dotsb$ comparisons per alignment, and why this is close to $\frac43$ .
7. Why is the result almost the same for every [pattern](#def-g12-text-search-pattern) length?
8. With $26$ letters, what number replaces $\frac43$ ? Compare with the output of `compare_counts.py` .

**Part III — Horspool’s search.**

9. The mean jump is the average of the [shift table](#def-g12-text-search-shift-table) over the four letters. Compute it for the [pattern](#def-g12-text-search-pattern) `ACGTACGT` .
10. At each alignment Horspool makes a little more than one comparison. Explain why its count per letter is about $1.4$ divided by the mean jump, and check it on the output.
11. Why does the mean jump grow from $m = 4$ to $m = 16$ , and then stop growing?
12. Why can no shift exceed $m$ , and why, with four letters, are shifts above $10$ rare for long [patterns](#def-g12-text-search-pattern) ?
13. Which [pattern](#def-g12-text-search-pattern) of length $8$ has the largest mean jump? Give its [shift table](#def-g12-text-search-shift-table) .

**Part IV — The ratio.**

14. Read the ratio of the two counts for each $m$ .
15. Compare with the chart for $26$ letters: what would the ratio be at $m = 32$ there?
16. The count for $m = 32$ is higher than for $m = 16$ . Is the search worse for long [patterns](#def-g12-text-search-pattern) ? What does the variation say about five [patterns](#def-g12-text-search-pattern) per length?
17. The comparisons are counted, not timed. Which listing of the chapter shows that the two do not tell the same story, and why?
18. What text and [pattern](#def-g12-text-search-pattern) would make Horspool’s count per letter close to $m$ ?
19. Why would a real program use `str.find` rather than either of these functions?
20. State the result: comparisons per letter of the two searches on the chain, their ratio, and how it depends on the [pattern](#def-g12-text-search-pattern) ’s length.

**Solution of Problem 29.1.**

**1.** So that each [pattern](#def-g12-text-search-pattern) occurs at least once: a random [pattern](#def-g12-text-search-pattern) of $16$ letters would almost never occur, and the search for an [occurrence](#def-g12-text-search-pattern) would not be tested.

**2.** Each position starts a given $4$-letter [pattern](#def-g12-text-search-pattern) with chance $1/4^4 = 1/256$: about $100\,000 / 256 \approx
390$ [occurrences](#def-g12-text-search-pattern). $378$ is close.

**3.** The chance at a position is $1/4^{16}$, about $2 \times 10^{-10}$; over a million positions, about $2 \times 10^{-4}$.

**4.** That both searches find the same positions; a speed-up that loses [occurrences](#def-g12-text-search-pattern) would be worthless, and the check runs on every [pattern](#def-g12-text-search-pattern).

**5.** $\frac34$ that the first fails; $\frac14$ that a second comparison is made, $\frac1{16}$ a third.

**6.** The $k$-th comparison is made when the first $k - 1$ agree, with chance $(1/4)^{k-1}$. Adding these chances gives the mean number of comparisons: $1 + \frac14 + \frac1{16} + \dotsb = \frac{1}{1 - 1/4} = \frac43$, the terms beyond $m$ being negligible.

**7.** The sum is almost all in its first terms; the [pattern](#def-g12-text-search-pattern)’s length only cuts it off far away.

**8.** $\frac{1}{1 - 1/26} = \frac{26}{25} = 1.04$, the value printed.

**9.** The first seven places `ACGTACG`: `A` last at $4$, shift $3$; `C` at $5$, $2$; `G` at $6$, $1$; `T` at $3$, $4$. Mean $(3 + 2 + 1 + 4)/4 = 2.5$.

**10.** The search makes one alignment per jump, so about $n / \text{(mean jump)}$ alignments, each with a little more than $\frac43$ comparisons, about $1.4$ to $1.5$. Divided by $n$: $1.4 / 2.75 \approx 0.51$ for $m = 4$, $1.4 / 3.6 \approx 0.39$ for $m = 8$, $1.4 / 4.25 \approx 0.33$ for $m = 16$; the printed values are $0.514$, $0.412$, $0.363$.

**11.** For $m = 4$, the shifts cannot exceed $4$. As $m$ grows, they may; but each letter’s last place is usually within the last few places (exercise [29.15](#exo-g12-text-search-15)), so the mean stops near $4$.

**12.** A shift is $m - 1 - j$ with $j \ge 0$, or $m$: at most $m$. A shift above $10$ means a letter absent from the $10$ places before the last, with chance $(3/4)^{10} \approx 0.06$ for each letter.

**13.** A [pattern](#def-g12-text-search-pattern) whose first seven letters are all the same, such as `AAAAAAAA`: `A` gets $1$ and the three other letters $8$, mean $6.25$. A letter present among the first seven places gets at least $1$, and only one letter can have all its places early if all seven are filled.

**14.** $2.6$, $3.2$, $3.7$, $3.4$.

**15.** About $1.04 / 0.057 \approx 18$.

**16.** No: five [patterns](#def-g12-text-search-pattern) per length are few, and the mean jump varies from [pattern](#def-g12-text-search-pattern) to [pattern](#def-g12-text-search-pattern) ($4.25$ against $3.80$ here). The differences between $m = 16$ and $m = 32$ are within that variation.

**17.** `measure_find.py`: `str.find` makes comparisons of the same kind, but in machine code, without the work of the Python interpreter around each step.

**18.** A text of a single letter repeated, with a [pattern](#def-g12-text-search-pattern) of the same letter except the first (exercise [29.13](#exo-g12-text-search-13)): $m$ comparisons per alignment and jumps of $1$.

**19.** It gives the same answers, is tested by millions of programs, and is many times faster.

**20.** **On a million random letters from A, C, G, T, the naive search makes $1.33$ comparisons per letter whatever the [pattern](#def-g12-text-search-pattern); Horspool’s makes $0.51$ for [patterns](#def-g12-text-search-pattern) of $4$ letters and $0.36$ to $0.41$ for $8$ to $32$: $2.6$ to $3.7$ times fewer, levelling off because its mean jump stays near $4$ places. On $26$ letters the saving grows with the [pattern](#def-g12-text-search-pattern) instead.**
