问题遇到的现象和发生背景
不会做题,要交作业了。哪位大神康康能不能把这个BP算法的改成KMP算法的,是做病毒检测的。
max_size = 100
class SString:
def __init__(self):
# 初始化一个空的串
self.length = 0 # 串当前长度
self.ch = [None] * max_size # 最大长度为max_size的空间
def str_assign(self, s):
# 把串的值赋为s
n = len(s) # 求串s的长度
if n > max_size - 1: # 此处为max_size - 1因为0号单元弃用
raise Exception('空间已满')
else:
self.length = 0 # 把串置为空
while self.length < n:
self.length += 1
self.ch[self.length] = s[self.length - 1]
return self
def index_bf(s, t, pos):
# 返回模式t在主串s中第pos个字符之后第s一次出现的位置。若不存在,则返回值为0
# 其中,t非空,1≤pos≤s.length
i = pos
j = 1 # 初始化
print("bf:",s.ch[1:s.length],t.ch[1:t.length])
while i <= s.length and j <= t.length: # 两串均未比较到串尾
if s.ch[i] == t.ch[j]:
i += 1
j += 1 # 继续比较后继字符
else:
i = i - j + 2
j = 1 # 指针后退重新开始匹配
if j > t.length:
return i - t.length # 匹配成功
else:
return 0 # 匹配失败
def virus_detection(v, p):
# 利用BF算法实现病毒检测
virus = SString()
person = SString()
virus.str_assign(v) # 读取病毒DNA序列
person.str_assign(p) # 读取人的DNA序列
flag = 0 # 用来标识是否匹配,初始为0,匹配后为非0
m = virus.length # 病毒DNA序列的长度是m
for i in virus.ch[1: m + 1]: # 病毒序列扩展到原来的2倍
virus.length += 1
virus.ch[virus.length] = i
j = 1
while j <= m: # 依次取得每个长度为m的病毒DNA环状字符串temp
temp = SString()
temp.str_assign(virus.ch[j:j + m])
flag = index_bf(person, temp, 1) # 模式匹配
if flag: # 匹配即可退出循环
break
j += 1
if flag:
print('YES')
else:
print('NO')
if __name__ == '__main__':
v, p = 'baa', 'bbaabbba'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='\n')
virus_detection(v, p)
v, p = 'baa', 'aaabbbba'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'aabb', 'abceaabb'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'aabb', 'abaabcea'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'abcd', 'cdabbbab'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'abcd', 'cabbbbab'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'abcde', 'bcdedbda'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'acc', 'bdebdcda'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'cde', 'cdcdcdec'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
v, p = 'cced', 'cdccdcce'
print('{v} {p}的检测结果为:'.format(v=v, p=p), end='')
virus_detection(v, p)
def kmp(s,t,pos):
k = 0
j = 1
n = [0]*(t.length+1)
while j<t.length:
if k==0 or t.ch[j]==t.ch[k]:
k += 1
j += 1
if t.ch[j] == t.ch[k]:
n[j] = n[k]
else:
n[j] = k
else:
k = n[k]
i = pos
j = 1
while i<=s.length and j<=t.length:
if j==0 or s.ch[i]==t.ch[j]:
i += 1
j += 1
else:
j = n[j]
if j>t.length:
return i-t.length
else:
return 0