Skip to content

Instantly share code, notes, and snippets.

@giuscri
Last active July 23, 2017 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuscri/321a51a140fab4435f36db7a29cc7061 to your computer and use it in GitHub Desktop.
Save giuscri/321a51a140fab4435f36db7a29cc7061 to your computer and use it in GitHub Desktop.
A collection of string matching algorithms taken from chapter 32 of CSLR.
from functools import reduce
from string import ascii_lowercase
def naive_string_matching(T, P):
"""Computes all the occurrences of P in T.
Cost of this procedure is O(n-m+1 * m)
where n, m are the length of T and of P
respectively.
Args:
T: text into which find occurrences.
P: substring to search in T.
Returns:
A list containing the indexes at which
the occurrences of P in T start. The actual
substrings can be derived via mapping
each element x of the returned list to T[x:x+len(P)].
"""
shifts = []
s, n, m = 0, len(T), len(P)
assert m <= n, 'substring is longer than string'
while s < n-m+1:
if T[s] != P[0]: s += 1; continue
j = 1
while j < m:
if T[s+j] != P[j]: break
j += 1
if j == m: shifts.append(s)
s += 1
return shifts
def rabin_karp_matching(T, P, q=997):
"""Computes all the occurrences of P in T.
Cost of this procedure is O(n-m+1 * m)
where n, m are the length of T and of P
respectively.
The idea behind Rabin-Karp is to leverage
comparisons between computer WORD's that
are supposed to happen in constant time.
Thus a numeric fingerprint is computed
for the pattern P and for each substring
of T of length m. In case fingerprints
match, the original pattern and the substring
of T that generated one of the fingerprints
are compared byte by byte.
Assuming comparison of two strings happen in O(m),
the worst case running time is computed assuming
that for each substring of T of length m (i.e.
n-m+1 substrings) a match of fingerprints will
happen, forcing a O(m) comparison n-m+1 times.
"""
T, P = T.encode('ASCII'), P.encode('ASCII')
n, m = len(T), len(P)
valid_shifts = []
p = reduce(lambda ac, x, q=q: (ac*128 + x) % q, P)
t_list = [reduce(lambda ac, x, q=q: (ac*128 + x) % q, T[:m])]
for s in range(n-m):
t = (t_list[-1]*128 + T[m+s] - pow(128, m, q) * T[s]) % q
t_list.append(t)
for s, t in enumerate(t_list):
if t == p and T[s:s+m] == P:
valid_shifts.append(s)
return valid_shifts
def is_suffix(a, b):
"""Computes whethere a is suffix of b"""
n = len(b)
return a == b[n-len(a):]
def build_delta(P, sigma=ascii_lowercase):
"""Build the transition function 𝛿 for the DFA of P.
𝛿(q, a) tells you the maximum number of characters
that can act as a suffix for P[:q]+a.
"""
delta, m = {}, len(P)
for q in range(m+1):
for a in sigma:
k = min(m, q+1)
while not is_suffix(P[:k], P[:q]+a):
k = k - 1
delta[(q, a)] = k
return lambda q, a, delta=delta: delta[(q, a)]
def dfa_matching(T, P):
"""Computes all the occurrences of P in T."""
delta = build_delta(P)
valid_shifts, q, m = [], 0, len(P)
for i, c in enumerate(T):
q = delta(q, c)
if q == m: valid_shifts.append(i-m+1)
return valid_shifts
def build_pi(P):
"""Build the prefix function π, as described in CSLR.
π(q) tells you the maximum number of characters
that can act as a *proper* suffix for P[:q].
"""
pi, m = [None], len(P)
for q in range(1, m+1):
k = q-1
while not is_suffix(P[:k], P[:q]):
k -= 1
pi.append(k)
return lambda q, pi=pi: pi[q]
def kmp_matching(T, P):
"""Computes all the occurrences of P in T."""
pi, n, m, q = build_pi(P), len(T), len(P), 0
valid_shifts = []
for i in range(n):
while q > 0 and P[q] != T[i]:
q = pi(q)
if P[q] == T[i]:
q += 1
if q == m:
valid_shifts.append(i+1-m)
q = pi(m)
return valid_shifts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment