W = "acabacacd"
T = "acfacabacabacacdk"
# this method is from above code snippet.
aux = creatAux(W)
# counter for word W
i = 0
# counter for text T
j = 0
while j < len(T):
# We need to handle 2 conditions when there is a mismatch
if W[i] != T[j]:
# 1st condition
if i == 0:
# starting again from the next character in the text T
j += 1
else:
# aux[i-1] will tell from where to compare next
# and no need to match for W[0..aux[i-1] - 1],
# they will match anyway, that’s what kmp is about.
i = aux[i-1]
else:
i += 1
j += 1
# we found the pattern
if i == len(W):
# printing the index
print "found pattern at " + str(j - i)
# if we want to find more patterns, we can
# continue as if no match was found at this point.
i = aux[i-1]