# general computation of an overlap function def overlap_function(pattern): ol_list = [0] * len(pattern) pos = 1 # first is always zero while (pos < len(pattern)): ol_prev = ol_list[pos - 1] if pattern[pos] == pattern[ol_prev]: ol_list[pos] = ol_prev + 1 else: found = False j = ol_prev curr_overlap = ol_prev while not found and j >= 1: # try extend a smaller prefix - based on pattern [ol[pos-1]] if pattern[pos] == pattern[j]: found = True ol_list[pos] = curr_overlap + 1 else: curr_overlap = ol_list[j-1] j = ol_list[j-1] if not found: # compare with the first if pattern[pos] == pattern[0]: ol_list[pos] = 1 pos += 1 return ol_list if __name__ == '__main__': ol_list = overlap_function('catcapcatcarcatcapcatcat') print (ol_list)