algorithm-in-python/algorithm/sunday.py
2018-07-11 19:26:24 +08:00

58 lines
1.5 KiB
Python

''' mbinary
#########################################################################
# File : sunday.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.coding.me
# Github: https://github.com/mbinary
# Created Time: 2018-07-11 15:26
# Description: 字符串模式匹配, sunday 算法, kmp 的改进
# pattern matching for strings using sunday algorithm
#########################################################################
'''
def getPos(pattern):
dic = {}
for i,j in enumerate(pattern[::-1]):
if j not in dic:
dic[j]= i
return dic
def find(s,p):
dic = getPos(p)
ps = pp = 0
ns = len(s)
np = len(p)
while ps<ns and pp<np:
if s[ps] == p[pp]:
ps,pp = ps+1,pp+1
else:
idx = ps-pp+np
if idx >=ns:return -1
ch = s[idx]
if ch in dic:
ps += dic[ch]+1-pp
else:
ps += np-pp
pp = 0
if pp==np:return ps-np
else:
return -1
def test():
s = [randint(78,88) for i in range(30)]
p = [randint(78,88) for i in range(3)]
str_s = ''.join((chr(i) for i in s))
str_p = ''.join((chr(i) for i in p))
n1 = find(s,p)
n2 = str_s.find(str_p)
if n1!=n2:
print(n1,n2,str_p,str_s)
return False
return True
if __name__ =='__main__':
from random import randint
n = 10000
suc = sum(test() for i in range(n))
print(f'test {n} times, success {suc} times')