以前有与此主题相关的问题,但是他们并没有消除我的疑问 我的代码与文本中的模式不匹配,仅当模式在文本开头时除外。我得到的模式的哈希值出现在与我在代码开始时计算出的值不同的文本中 例如:文字-abcabcabcabcabc 模式-abc 我将计数从1改为5
txt=input()
ptrn=input()
d=256
q=pow(2,30) #mod
h=0 #hash for pattern
ht=0 #hash for text
count=0
l=1
#calculating hash value for pattern
for i in ptrn:
h=(h+ord(i)*pow(d,l,q))%q
l+=1
l=1
#checking for first len(pattern) characters in text
for i in range(len(ptrn)):
ht=(ht+ord(txt[i])*pow(d,l,q))%q
l+=1
if(ht==h):
count+=1
#moving the window for all substrings
for i in range(len(ptrn),len(txt)):
ht=(ht/d-ord(txt[i-len(ptrn)])+ord(txt[i])*pow(d,len(ptrn),q))%q
if(ht==h):
count+=1
print(count)