এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
High School Computer Science · শ্রেণি 10–12
29Searching 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, and that much is proved.
You already know
A string is a sequence of characters, indexed from ; s[i:j] is the slice from up to (Book 1, grade 7; chapter 5). The cost of an algorithm is counted in elementary steps, as a function of the size of its input (chapter 17). 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 , in a text of length . An occurrence of the pattern is a position of the text with text[i:i + m] == p. Placing the pattern under the text from position is called an alignment; there are of them.
The naive search tries every alignment, from left to right. At each one it compares the letters of the pattern with those of the text above them, from the first, and gives up at the first difference.
"""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"))
$ python naive.py
([3, 10, 16, 22], 35)
([15], 27)
([21], 28) ([], 24)
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 letters a, the pattern aa...ab costs comparisons at each of the alignments.
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)
$ 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
29.2 Looking at the pattern first
Suppose the 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 under that K fails; the pattern can jump past it, seven places at once. If the letter were a T, the pattern could jump until its own last T, not counting the final place, comes under it: three places.
These distances depend on the pattern only, so they can be computed once, before reading the text. Doing work on the pattern in advance to save work on the text is called preprocessing.
Definition 29.2 (Shift table)
The shift table of a pattern of length gives, for each letter , the distance from the last place of in , the final place excluded, to the final place: , where is that last place. A letter absent from the first places of gets the shift .
"""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))
$ 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
T of STATION overwrote the earlier one.STATION (). The last T before the final place is at , three places from the end: shift . N, which appears only in the final place (shaded), and every letter absent from the pattern get .29.3 The Boyer–Moore–Horspool search
Method 29.3 (Boyer–Moore–Horspool)
The Boyer–Moore–Horspool algorithm computes the shift table of the pattern, then places the pattern at position and repeats while : compare the pattern with the text above it from right to left, and record if all letters agree; then, whatever happened, read the text letter under the pattern’s last place and move the pattern places to the right.
"""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"))
$ 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)
station in letters; then the, three times.station. At position , the first step of the trace, the text letter under the last place is s; the pattern’s only s is places from its end, so the pattern jumps places, bringing its s under the text’s s. Any smaller jump would put some other letter of the pattern under that s.Why are no occurrences skipped? Let be the text letter under the last place, at alignment , and its shift. For a jump of places with , the letter of the pattern that would come under is at place , which is not the last place and lies after the last place of among the first ; so it is not , and that alignment fails. The alignments jumped over all fail, and the search tries every one that could succeed (exercise 29.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 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 letters, from letters and from four (A, C, G, T, as in genetic sequences), and cuts the patterns from the texts so that each occurs at least once.
"""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)}")
$ 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
figures/per_letter.py. The naive search stays near and whatever the pattern. With letters Horspool’s count falls roughly like , to at ; with four letters it stays around .The jump is long only when the letter under the last place is rare in the pattern. With letters, most text letters do not appear in a short pattern at all, and the pattern jumps its whole length. With four letters, every letter appears among the last few places of any long pattern, so the jumps stay short, about four places, however long the pattern. The worst case is as bad as the naive search’s: in a text of as, the pattern baa...a costs comparisons at each alignment and jumps one place (exercise 29.13).
On the titles of the town library, joined into one text, the counts are those of ordinary text.
"""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}")
$ 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]
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.
"""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")
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
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 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 overlap?
Solution
Solution of Exercise 29.1.
At positions and : b[ana]nas and ban[ana]s. They overlap: the a at position belongs to both.
Exercise 29.2 ★
Count the comparisons of search_naive("abcabd", "abd").
Solution
Solution of Exercise 29.2.
Position : a, b agree, c differs from d: . Positions and : one each. Position : a, b, d agree: , found. In all comparisons, and the occurrence .
Exercise 29.3 ★
Write the shift table of BANANA.
Solution
Solution of Exercise 29.3.
The first five places are BANAN. B is last at : . A is last at : . N is last at : . Every other letter: .
Exercise 29.4 ★
List the alignments Horspool’s search tries for TOWN in THE OLD TOWN HALL, and the jump after each.
Solution
Solution of Exercise 29.4.
The table of TOWN: T , O , W , others . Position : the space under the last place, no match, jump . Position : under the last place, the space after OLD, jump . Position : TOWN, found; under the last place an N, jump . Position : an L, jump , and ends the search. Four alignments.
Exercise 29.5 ★
Write count_occurrences(text, p) with slices, trying every position.
Solution
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 are missed? Give the smallest test that catches it.
Solution
Solution of Exercise 29.6.
The last alignment, , is never tried: an occurrence at the very end of the text is missed. The smallest test is a text equal to the pattern, such as search("a", "a"), which must find ; "the town" with "town" also catches it.
Exercise 29.7 ★★
Write horspool_first(text, p), which returns the first occurrence, or , and stops as soon as it is found.
Solution
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 on random cases.
Exercise 29.8 ★★
A student builds the 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
Solution of Exercise 29.8.
N is at the last place, , and gets . When an N of the text comes under the last place (for instance once TOWN is found), the pattern moves places: the same alignment is tried again, for ever. The last place must be left out, so that every shift is at least .
Exercise 29.9 ★★
For a text of letters, which pattern length makes the worst case of the naive search, , the largest? How many comparisons for ?
Solution
Solution of Exercise 29.9.
is largest for near , the middle of its two roots and . For : or , and comparisons, a quarter of .
Exercise 29.10 ★★
Where does ABAB occur in ABABABAB, by the naive search? What does "ABABABAB".count("ABAB") return, and why the difference?
Solution
Solution of Exercise 29.10.
At , and . count returns : it counts occurrences that do not overlap, so after the one at it resumes at . A search for every occurrence 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
Solution of Exercise 29.11.
def search_ignore_case(text, p):
return horspool(text.lower(), p.lower())[0]
It returns . 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: no alignment it jumps over is an occurrence.
Solution
Solution of Exercise 29.12.
Let the search be at alignment , let be the text letter at , under the pattern’s last place, and . Take an alignment with . Under the text letter it puts the pattern’s place , which is between and . If appears among the first places, its last place there is , so the places from to hold no ; if it does not appear, no place does. Either way the pattern’s letter under is not , and alignment is not an occurrence. So the alignments jumped over are not occurrences, and every alignment not jumped over is checked letter by letter.
Exercise 29.13 ★★★
Show that for the text of letters a and the pattern b followed by letters a, Horspool’s search makes exactly comparisons.
Solution
Solution of Exercise 29.13.
At every alignment the window is letters a. Comparing from the right, the last places of the pattern are a and agree, and the first, b, does not: comparisons. The letter under the last place is a, whose last place among the first is : shift . So every one of the alignments is tried, at comparisons each. The tests check for three pairs .
Exercise 29.14 ★★★
Write search_wildcard(text, p), in which a ? of the pattern matches any one letter. Why does the shift table not work directly with a ??
Solution
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 needs that the pattern’s letter under is not ; a ? matches every . A ? at place limits every shift to at most ; the table must be built that way, or the search must stay naive. st? finds and 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. Explain why, and measure the mean jump for one pattern of length .
Solution
Solution of Exercise 29.15.
A letter’s shift is its distance from the end, counted from its last place among the first . In a random pattern each place holds a given letter with chance , so the last place of that letter is usually within the last few places: places , , … each miss it with chance . The shifts are about to whatever , and their mean about . For one pattern of length cut from a random text of letters, the shift table was C , G , T , A , mean ; over the jumps of the search, the measured mean was .
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 of each length from it, and runs both searches.
"""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}")
$ 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
Part I — The chain.
- Why are the patterns cut from the text rather than drawn at random?
- In a random chain, how often would you expect a given pattern of letters? Compare with the found in the letters of
compare_counts.py. - Why is a pattern of letters very unlikely to occur twice?
- What does
assert found == found_hcheck, and why is it in the program?
Part II — The naive search.
- At an alignment, what is the chance that the first comparison fails? That the search reaches a second comparison? A third?
- Explain why the naive search makes about comparisons per alignment, and why this is close to .
- Why is the result almost the same for every pattern length?
- With letters, what number replaces ? Compare with the output of
compare_counts.py.
Part III — Horspool’s search.
- The mean jump is the average of the shift table over the four letters. Compute it for the pattern
ACGTACGT. - At each alignment Horspool makes a little more than one comparison. Explain why its count per letter is about divided by the mean jump, and check it on the output.
- Why does the mean jump grow from to , and then stop growing?
- Why can no shift exceed , and why, with four letters, are shifts above rare for long patterns?
- Which pattern of length has the largest mean jump? Give its shift table.
Part IV — The ratio.
- Read the ratio of the two counts for each .
- Compare with the chart for letters: what would the ratio be at there?
- The count for is higher than for . Is the search worse for long patterns? What does the variation say about five patterns per length?
- The comparisons are counted, not timed. Which listing of the chapter shows that the two do not tell the same story, and why?
- What text and pattern would make Horspool’s count per letter close to ?
- Why would a real program use
str.findrather than either of these functions? - State the result: comparisons per letter of the two searches on the chain, their ratio, and how it depends on the pattern’s length.
Solution
Solution of Problem 29.1.
1. So that each pattern occurs at least once: a random pattern of letters would almost never occur, and the search for an occurrence would not be tested.
2. Each position starts a given -letter pattern with chance : about occurrences. is close.
3. The chance at a position is , about ; over a million positions, about .
4. That both searches find the same positions; a speed-up that loses occurrences would be worthless, and the check runs on every pattern.
5. that the first fails; that a second comparison is made, a third.
6. The -th comparison is made when the first agree, with chance . Adding these chances gives the mean number of comparisons: , the terms beyond being negligible.
7. The sum is almost all in its first terms; the pattern’s length only cuts it off far away.
8. , the value printed.
9. The first seven places ACGTACG: A last at , shift ; C at , ; G at , ; T at , . Mean .
10. The search makes one alignment per jump, so about alignments, each with a little more than comparisons, about to . Divided by : for , for , for ; the printed values are , , .
11. For , the shifts cannot exceed . As grows, they may; but each letter’s last place is usually within the last few places (exercise 29.15), so the mean stops near .
12. A shift is with , or : at most . A shift above means a letter absent from the places before the last, with chance for each letter.
13. A pattern whose first seven letters are all the same, such as AAAAAAAA: A gets and the three other letters , mean . A letter present among the first seven places gets at least , and only one letter can have all its places early if all seven are filled.
14. , , , .
15. About .
16. No: five patterns per length are few, and the mean jump varies from pattern to pattern ( against here). The differences between and 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 of the same letter except the first (exercise 29.13): comparisons per alignment and jumps of .
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 comparisons per letter whatever the pattern; Horspool’s makes for patterns of letters and to for to : to times fewer, levelling off because its mean jump stays near places. On letters the saving grows with the pattern instead.