I tried again to implement the algorithm. Just need someone to check my work. I hope I didn't miss anything but my long work hours recently have been pretty taxing on my brain so I honestly wouldn't be surprised if I messed up somehow.
def KMP_table(wrd):
#example: B A A B D C B A A A C A B -> [-1, 0, 0, -1, 1, 2, -1, 0, 0, 0, 4, 5, -1]
table = []
position, candidate = 0, 0
while position < len(wrd):
if wrd[candidate] == wrd[position]:
table.append(-1)
candidate += (position - candidate)
elif wrd[position] == wrd[position - candidate] or candidate == 0:
table.append(0)
else:
table.append(position - candidate)
position += 1
return table
def KMP_search(wrd, str):
if not wrd or not str:
raise ValueError("Empty lists")
w, s = 0, 0
lenWrd, lenStr = len(wrd), len(str)
wrdPos = []
table = KMP_table(wrd)
while (s + lenWrd-1) < lenStr:
if wrd[w] == str[w + s]:
if w == lenWrd - 1:
wrdPos.append(s)
s += 1
w = 0
else:
w += 1
else:
if table[w] > 0:
s += (w - table[w])
elif w == 0:
s += 1
else:
s += w
w = 0
return wrdPos