1. KMP Algorithm
Code
Def compute_prefix_function (p ):
M = len (p)
Pi = [0] * m
K = 0
For q in range (1, m ):
While k> 0 and p [k]! = P [q]:
K = pi [k-1]
If p [k] = p [q]:
K = k + 1
Pi [q] = k
Return pi
Def kmp_matcher (t, p ):
N = len (t)
M = len (p)
Pi = compute_prefix_function (p)
Q = 0
For I in range (n ):
While q> 0 and p [q]! = T [I]:
Q = pi [q-1]
If p [q] = t [I]:
Q = q + 1
If q = m:
Return I-m + 1
Return-1
2. BM algorithm example
Code
Def BoyerMooreHorspool (pattern, text ):
M = len (pattern)
N = len (text)
If m> n: return-1
Skip = []
For k in range (256): skip. append (m)
For k in range (m-1): skip [ord (pattern [k])] = m-k-1
Skip = tuple (skip)
K = m-1
While k <n:
J = m-1; I = k
While j> = 0 and text [I] = pattern [j]:
J-= 1; I-= 1
If j =-1: return I + 1
K + = skip [ord (text [k])]
Return-1
If _ name _ = '_ main __':
Text = "this is the string to search in"
Pattern = ""
S = BoyerMooreHorspool (pattern, text)
Print 'text: ', Text
Print 'pattern', Pattern
If s>-1:
Print 'pattern' + Pattern + '\ "found at position', s
These two algorithms are mainly used for string matching. Online comments said that the BM performance is better than KMP, and I have not verified it. You can test it with cProfile another day.
Ps: Today we use these two algorithms to find the last line of string in the 69K document. KMP uses 0.053 CPU times and BM only uses 0.025 CPU times.
In fact, I would like to take a look at the Sunday algorithm. It is said that it is an improvement of BM, improving a lot of performance. After studying the algorithm, there is more human nature. But now there is no python implementation on the Internet, so try another one in the next day.