''' This code explores the KMP algorithm idea, assuming that the overlap function has been precomputed. It uses 3 index variables - i - for current position in T j -for current position in P k - start of a potential match ''' __author__ = "Marina Barsky, and Catherine Liu" T = 'tictictictactictictic' P = 'tictic' #for visualization purposes, we convert the strings to lists of characters #to better see them in the visualizer: https://goo.gl/iVonii T = list(T) P = list(P) M = len(P) N = len(T) of_list = [0, 0, 0, 1, 2, 3] # manually precomputed overlap function # algorithm i = 0 #current position at which to compare character in T j = 0 #current position at which to compare character in P k = 0 #start position of a potential match in T while N - k >= M: #while start position is M characters from the end of T #loop while characters match while j < M and T[i] == P[j]: i = i + 1 j = j + 1 if j == M: print("Found match at position", (i - M)) of_prev = of_list[j-1] if of_prev == 0: # not even first character match i = i + 1 k = i j = 0 else: k = i - of_prev i = k + of_prev j = of_prev