-
Notifications
You must be signed in to change notification settings - Fork 47
/
KMP_Algoritm.py
61 lines (51 loc) · 1.55 KB
/
KMP_Algoritm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def calculateLps(pattern, lps):
# length of previous lps
length = 0
lps[0] = 0
iterator = 1
while iterator < len(pattern):
if pattern[iterator] == pattern[length]:
length += 1
lps[iterator] = length
iterator += 1
else:
if length != 0:
# iterator is not incremented here
length = lps[length - 1]
else:
lps[iterator] = 0
iterator += 1
# this is the function used to check if pattern is there in text
def KMPSearch(pattern, text):
sizePattern = len(pattern)
sizeText = len(text)
# lps will hold the longest prefix suffix values for pattern
lps = [0] * sizePattern
j = 0
# this function will calculate the longest prefix suffix
calculateLps(pattern, lps)
i = 0
while i < sizeText:
if pattern[j] == text[i]:
i+=1
j+=1
if j == sizePattern:
print("Pattern found at " + str(i - j + 1)) # print the pattern starting index
j = lps[j - 1]
elif i < sizeText and pattern[j] != text[i]:
if j != 0:
j = lps[j - 1]
else:
i += 1
#for dynamic input use the below code
text =input("Enter the input string : ")
pattern = input("Enter the string to be searched : ")
KMPSearch(pattern, text)
# text = "aaanunaanuaunnanuubhanu"
# pattern = "anu"
# KMPSearch(pattern, text)
# ''' Output
# Pattern found at 3
# Pattern found at 8
# Pattern found at 15
# Pattern found at 21