কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 00; s[i:j] is the slice from ii up to jj (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 mm, in a text of length nn. An occurrence of the pattern is a position ii of the text with text[i:i + m] == p. Placing the pattern under the text from position ii is called an alignment; there are n−m+1n - m + 1 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"))
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 2727 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.
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 nn letters a, the pattern aa...ab costs mm comparisons at each of the n−m+1n - m + 1 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)
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)×m(n - m + 1) \times m comparisons.

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 pp of length mm gives, for each letter cc, the distance from the last place of cc in pp, the final place excluded, to the final place: m−1−jm - 1 - j, where jj is that last place. A letter absent from the first m−1m - 1 places of pp gets the shift mm.

"""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, 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.
The shift table of STATION (m=7m = 7). The last T before the final place is at 33, three places from the end: shift 33. N, which appears only in the final place (shaded), and every letter absent from the pattern get 77.

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 i=0i = 0 and repeats while i≤n−mi \le n - m: compare the pattern with the text above it from right to left, and record ii if all mm letters agree; then, whatever happened, read the text letter cc under the pattern’s last place and move the pattern shift(c)\mathrm{shift}(c) 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"))
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 1313 comparisons to find station in 4545 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.
A jump of Horspool’s search for station. At position 00, the first step of the trace, the text letter under the last place is s; the pattern’s only s is 66 places from its end, so the pattern jumps 66 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 cc be the text letter under the last place, at alignment ii, and ss its shift. For a jump of dd places with 1≤d<s1 \le d < s, the letter of the pattern that would come under cc is at place m−1−dm - 1 - d, which is not the last place and lies after the last place of cc among the first m−1m - 1; so it is not cc, 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 100 000100\,000 letters, from 2626 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)}")
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 2626 letters, Horspool’s count falls as the 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.
Comparisons per text letter, averaged over five patterns for each length, on random texts of 50 00050\,000 letters, from figures/per_letter.py. The naive search stays near 1.041.04 and 1.331.33 whatever the pattern. With 2626 letters Horspool’s count falls roughly like 1/m1/m, to 0.060.06 at m=32m = 32; with four letters it stays around 0.40.4.

The jump is long only when the letter under the last place is rare in the pattern. With 2626 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 mm 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}")
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.

"""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 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 11 and 33: b[ana]nas and ban[ana]s. They overlap: the a at position 33 belongs to both.

Exercise 29.2 ★

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

Solution

Solution of Exercise 29.2.

Position 00: a, b agree, c differs from d: 33. Positions 11 and 22: one each. Position 33: a, b, d agree: 33, found. In all 88 comparisons, and the occurrence [3][3].

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 00: 55. A is last at 33: 22. N is last at 44: 11. Every other letter: 66.

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 33, O 22, W 11, others 44. Position 00: the space under the last place, no match, jump 44. Position 44: under the last place, the space after OLD, jump 44. Position 88: TOWN, found; under the last place an N, jump 44. Position 1212: an L, jump 44, and 16>17−416 > 17 - 4 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, i=n−mi = n - m, 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 [0][0]; "the town" with "town" also catches it.

Exercise 29.7 ★★

Write horspool_first(text, p), which returns the first occurrence, or −1-1, 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 400400 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, 33, and gets 4−1−3=04 - 1 - 3 = 0. When an N of the text comes under the last place (for instance once TOWN is found), the pattern moves 00 places: the same alignment is tried again, for ever. The last place must be left out, so that every shift is at least 11.

Exercise 29.9 ★★

For a text of nn letters, which pattern length mm makes the worst case of the naive search, (n−m+1)m(n - m + 1)m, the largest? How many comparisons for n=1000n = 1000?

Solution

Solution of Exercise 29.9.

(n−m+1)m(n - m + 1)m is largest for mm near (n+1)/2(n + 1)/2, the middle of its two roots 00 and n+1n + 1. For n=1000n = 1000: m=500m = 500 or 501501, and 501×500=250 500501 \times 500 = 250\,500 comparisons, a quarter of n2n^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

Solution of Exercise 29.10.

At 00, 22 and 44. count returns 22: it counts occurrences that do not overlap, so after the one at 00 it resumes at 44. 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 [4,17][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: no alignment it jumps over is an occurrence.

Solution

Solution of Exercise 29.12.

Let the search be at alignment ii, let cc be the text letter at i+m−1i + m - 1, under the pattern’s last place, and s=shift(c)s = \mathrm{shift}(c). Take an alignment i+di + d with 1≤d<s1 \le d < s. Under the text letter cc it puts the pattern’s place m−1−dm - 1 - d, which is between m−sm - s and m−2m - 2. If cc appears among the first m−1m - 1 places, its last place there is m−1−sm - 1 - s, so the places from m−sm - s to m−2m - 2 hold no cc; if it does not appear, no place does. Either way the pattern’s letter under cc is not cc, and alignment i+di + d 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 nn letters a and the pattern b followed by m−1m - 1 letters a, Horspool’s search makes exactly m(n−m+1)m(n - m + 1) comparisons.

Solution

Solution of Exercise 29.13.

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

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 cc is not cc; a ? matches every cc. A ? at place j<m−1j < m - 1 limits every shift to at most m−1−jm - 1 - j; the table must be built that way, or the search must stay naive. st? finds 1515 and 2323 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 3232.

Solution

Solution of Exercise 29.15.

A letter’s shift is its distance from the end, counted from its last place among the first m−1m - 1. In a random pattern each place holds a given letter with chance 14\frac14, so the last place of that letter is usually within the last few places: places m−2m - 2, m−3m - 3, … each miss it with chance 34\frac34. The shifts are about 11 to 88 whatever mm, and their mean about 44. For one pattern of length 3232 cut from a random text of 200 000200\,000 letters, the shift table was C 33, G 11, T 55, A 44, mean 3.253.25; over the 61 34361\,343 jumps of the search, the measured mean was 3.263.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 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}")
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.

Part I — The chain.

  1. Why are the patterns cut from the text rather than drawn at random?
  2. In a random chain, how often would you expect a given pattern of 44 letters? Compare with the 378378 found in the 100 000100\,000 letters of compare_counts.py.
  3. Why is a pattern of 1616 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.

  1. At an alignment, what is the chance that the first comparison fails? That the search reaches a second comparison? A third?
  2. Explain why the naive search makes about 1+14+116+⋯1 + \frac14 + \frac1{16} + \dotsb comparisons per alignment, and why this is close to 43\frac43.
  3. Why is the result almost the same for every pattern length?
  4. With 2626 letters, what number replaces 43\frac43? Compare with the output of compare_counts.py.

Part III — Horspool’s search.

  1. The mean jump is the average of the shift table over the four letters. Compute it for the pattern ACGTACGT.
  2. At each alignment Horspool makes a little more than one comparison. Explain why its count per letter is about 1.41.4 divided by the mean jump, and check it on the output.
  3. Why does the mean jump grow from m=4m = 4 to m=16m = 16, and then stop growing?
  4. Why can no shift exceed mm, and why, with four letters, are shifts above 1010 rare for long patterns?
  5. Which pattern of length 88 has the largest mean jump? Give its shift table.

Part IV — The ratio.

  1. Read the ratio of the two counts for each mm.
  2. Compare with the chart for 2626 letters: what would the ratio be at m=32m = 32 there?
  3. The count for m=32m = 32 is higher than for m=16m = 16. Is the search worse for long patterns? What does the variation say about five patterns per length?
  4. The comparisons are counted, not timed. Which listing of the chapter shows that the two do not tell the same story, and why?
  5. What text and pattern would make Horspool’s count per letter close to mm?
  6. Why would a real program use str.find rather than either of these functions?
  7. 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 1616 letters would almost never occur, and the search for an occurrence would not be tested.

2. Each position starts a given 44-letter pattern with chance 1/44=1/2561/4^4 = 1/256: about 100 000/256≈390100\,000 / 256 \approx 390 occurrences. 378378 is close.

3. The chance at a position is 1/4161/4^{16}, about 2×10−102 \times 10^{-10}; over a million positions, about 2×10−42 \times 10^{-4}.

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. 34\frac34 that the first fails; 14\frac14 that a second comparison is made, 116\frac1{16} a third.

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

7. The sum is almost all in its first terms; the pattern’s length only cuts it off far away.

8. 11−1/26=2625=1.04\frac{1}{1 - 1/26} = \frac{26}{25} = 1.04, the value printed.

9. The first seven places ACGTACG: A last at 44, shift 33; C at 55, 22; G at 66, 11; T at 33, 44. Mean (3+2+1+4)/4=2.5(3 + 2 + 1 + 4)/4 = 2.5.

10. The search makes one alignment per jump, so about n/(mean jump)n / \text{(mean jump)} alignments, each with a little more than 43\frac43 comparisons, about 1.41.4 to 1.51.5. Divided by nn: 1.4/2.75≈0.511.4 / 2.75 \approx 0.51 for m=4m = 4, 1.4/3.6≈0.391.4 / 3.6 \approx 0.39 for m=8m = 8, 1.4/4.25≈0.331.4 / 4.25 \approx 0.33 for m=16m = 16; the printed values are 0.5140.514, 0.4120.412, 0.3630.363.

11. For m=4m = 4, the shifts cannot exceed 44. As mm grows, they may; but each letter’s last place is usually within the last few places (exercise 29.15), so the mean stops near 44.

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

13. A pattern whose first seven letters are all the same, such as AAAAAAAA: A gets 11 and the three other letters 88, mean 6.256.25. A letter present among the first seven places gets at least 11, and only one letter can have all its places early if all seven are filled.

14. 2.62.6, 3.23.2, 3.73.7, 3.43.4.

15. About 1.04/0.057≈181.04 / 0.057 \approx 18.

16. No: five patterns per length are few, and the mean jump varies from pattern to pattern (4.254.25 against 3.803.80 here). The differences between m=16m = 16 and m=32m = 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 of the same letter except the first (exercise 29.13): mm comparisons per alignment and jumps of 11.

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.331.33 comparisons per letter whatever the pattern; Horspool’s makes 0.510.51 for patterns of 44 letters and 0.360.36 to 0.410.41 for 88 to 3232: 2.62.6 to 3.73.7 times fewer, levelling off because its mean jump stays near 44 places. On 2626 letters the saving grows with the pattern instead.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো