Monday, May 2, 2016

KMP Algorithm in Python

# author:           Marcin Cherek
# python version:   2.7.11
# Date:             2 of Mai 2016
# language:         English
# Title:            KMP Algorithm python implementation

#Build the Prefix table
def lspTable(pattern):
    lsp = [0] * len(pattern)
    lsp[0] = 0
    for i in range(1,len(pattern)):
        j = int(lsp[i-1])
        while(j>0 and pattern[i]!=pattern[j]):
            j=int(lsp[j-1])
        if(pattern[i] == pattern[j]):
            j+=1
        lsp[i]=j
    return lsp

def kpm_search(pattern, text):
    lsp = lspTable(pattern)
    j = 0
    for i in range(0,len(text)):
        while( j>0 and text[i] != pattern[j]):
            j = lsp[j-1]
        if(text[i]==pattern[j]):
            j+=1
            if(j==len(pattern)):
               return i-(j-1) #returns the position
    return -1 #Not found

No comments:

Post a Comment