I have a cost function Cost_Func(pt,STRING)
that calculates value in a specific way based on the given pattern string pt
and main string STRING
.
A mathematical expression ( y := y-11*int(STRING[i-length]))/6+ int(STRING[i])*pow(11,length)
, this is the main calculation ) is used,
and the intuition is, it will be faster than KMP string matching (to compare I present here the function KMPSearch(pt,STRING)
),
but to my surprise, it is not.
I thought KMP function would have to use a lot of value-comparison, while the expression y
runs through the loop once.
In the hope of better performance, I used assignment expressions in list comprehension (Python 3.8), but the function is still slower than the KMP matching function. I need to be faster than KMP function, otherwise the cost function will not be accepted.
txt = "010110101010101010100000000000111111111111111111111111111111111110000"
pat = "01000000000001"
import time
def Cost_Func(pt,STRING):
x=y=0
h,length,cnst=[],len(pt),3
[(x := x+pow(11*int(pt[i]),(i+1)),y := y+pow(11*int(STRING[i]),(i+1))) for i in range(length)]
h=[((i-length+1)) for i in range(length,len(STRING)) if (y := (y-11*int(STRING[i-length]))/6+ int(STRING[i])*pow(11,length))>x/cnst]
return h
def KMPSearch(pt, tt):
k=[]
M = len(pat)
N = len(txt)
lps = [0]*M
j = 0
computeLPSArray(pat, M, lps)
i = 0
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
if j == M:
k.append(i-j)
j = lps[j-1]
elif i < N and pat[j] != txt[i]:
if j != 0:
j = lps[j-1]
else:
i += 1
return k
def computeLPSArray(pat, M, lps):
len = 0
lps[0]
i = 1
while i < M:
if pat[i]== pat[len]:
len += 1
lps[i] = len
i += 1
else:
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1
k=200
t0 = time.time()
for i in range(1,k):
Cost_Func(pat,txt)
t1 = time.time()
for i in range(1,k):
KMPSearch(pat, txt)
t2 = time.time()
print("Cost_func:",(t1-t0)/k*10000,"KMP:",(t2-t1)/k*10000,k)
Is there a faster way to complete the Cost_Func(pt,STRING)
?
For example, would library like NumPy help? Is there any other technique?
The source of the code of KMP function is taken from here.