Optimized Naive Algorithm for Pattern Searching | Python program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver program to test the above function
def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE i = 0 NEW_LINE while i <= N - M : NEW_LINE INDENT for j in xrange ( M ) : NEW_LINE INDENT if txt [ i + j ] != pat [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if j == M : NEW_LINE INDENT print " Pattern ▁ found ▁ at ▁ index ▁ " + str ( i ) NEW_LINE i = i + M NEW_LINE DEDENT elif j == 0 : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = i + j NEW_LINE DEDENT DEDENT DEDENT txt = " ABCEABCDABCEABCD " NEW_LINE pat = " ABCD " NEW_LINE search ( pat , txt ) NEW_LINE