File tree 1 file changed +61
-0
lines changed
1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ #effective approach for pattern searching KMP(Knuth Morris Pratt) algorithm.Time complexity O(n)
2
+ def kmpsearch (out , pat ):
3
+ n = len (out )
4
+ m = len (pat )
5
+ #array for longest prefix suffix
6
+ p = [0 ]* m
7
+ compute (pat ,m ,p )
8
+ q = 0
9
+ i = 0
10
+ while i < n :
11
+ if pat [q ]== out [i ]:
12
+ q = q + 1
13
+ i = i + 1
14
+ else :
15
+ if q != 0 :
16
+ q = p [q - 1 ]
17
+ else :
18
+ i = i + 1
19
+ if q == m :
20
+ print ("pattern occurs at " + str (i - q ))
21
+ q = p [q - 1 ]
22
+ #function definition for preproscessing longest prefix suffix
23
+ def compute (pat ,m ,p ):
24
+
25
+ k = 1
26
+ l = 0
27
+ while k < m :
28
+ if pat [k ] <= pat [l ]:
29
+ l = l + 1
30
+ p [k ] = l
31
+ k = k + 1
32
+ else :
33
+ if l != 0 :
34
+ l = p [l - 1 ]
35
+ else :
36
+ p [k ] = 0
37
+ k = k + 1
38
+
39
+ #to find pattern from string out
40
+
41
+ #brute force for pattern searching .Time complexity O(m*(n-m+1))
42
+ def search (pat , str ):
43
+ m = len (pat )
44
+ n = len (str )
45
+
46
+ for i in range (n - m + 1 ):
47
+ j = 0
48
+
49
+ for j in range (0 , m ):
50
+ if (str [i + j ] != pat [j ]):
51
+ break
52
+
53
+ if (j == m - 1 ):
54
+ print ("Pattern found at" , i )
55
+
56
+ out = 'abcacdbacdabdacaabcdba'
57
+ pat = 'dba'
58
+ print ("by brute force" )
59
+ search (pat ,out )
60
+ print ("by kmp algo" )
61
+ kmpsearch (out ,pat )
You can’t perform that action at this time.
0 commit comments