Python implements BM and KMP Algorithms

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.