Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions day12/Python/KMP.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'''
@author prateek3255
@date 05/01/2018
'''

def kmp(string,pattern):
n=len(string)
m=len(pattern)
lps=calculateLPS(pattern)
i=0
j=0
while i<n:
if pattern[j]==string[i]:
i+=1
j+=1
if j==m:
return i-j
elif i<n and pattern[j]!=string[i]:
if j!=0:
j=lps[j-1]
else:
i+=1
return -1

def calculateLPS(pattern):
lps=[0]*len(pattern)
i=1
lenPat=0
while i<len(pattern):
if pattern[i]==pattern[lenPat]:
lenPat+=1
lps[i]=lenPat
i+=1
else:
if lenPat!=0:
lenPat=lps[lenPat-1]
else:
lps[i]=0
i+=1
return lps

print(kmp("helloworld","hello"))
print(kmp("helloworld","hop"))
print(kmp("ABABDABACDABABCABAB","ABABCABAB"))

14 changes: 14 additions & 0 deletions day12/Python/bruteForce.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'''
@author prateek3255
@date 05/01/2018
'''

def subStringSearch(string,pattern):
for i in range(len(string)-len(pattern)):
if string[i:i+len(pattern)]==pattern:
return i
return -1

print(subStringSearch("helloworld","hello"))
print(subStringSearch("helloworld","hop"))
print(subStringSearch("abcrxyzgf","xyz"))
68 changes: 68 additions & 0 deletions day12/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,27 @@ substringSearch ("helloworld", "world");
substringSearch ("abcrxyzgf", "xyz");
```

### Python Implementation

#### [Solution](./Python/bruteForce.py)

```py
'''
@author prateek3255
@date 05/01/2018
'''

def subStringSearch(string,pattern):
for i in range(len(string)-len(pattern)):
if string[i:i+len(pattern)]==pattern:
return i
return -1

print(subStringSearch("helloworld","hello"))
print(subStringSearch("helloworld","hop"))
print(subStringSearch("abcrxyzgf","xyz"))
```

## B) Knuth-Morris-Pratt Algorithm

### JavaScript Implementation
Expand All @@ -85,6 +106,53 @@ substringSearch ("abcrxyzgf", "xyz");
To Be Added
```

### Python Implementation

#### [Solution](./Pyhton/KMP.py)

```py
def kmp(string,pattern):
n=len(string)
m=len(pattern)
lps=calculateLPS(pattern)
i=0
j=0
while i<n:
if pattern[j]==string[i]:
i+=1
j+=1
if j==m:
return i-j
elif i<n and pattern[j]!=string[i]:
if j!=0:
j=lps[j-1]
else:
i+=1
return -1

def calculateLPS(pattern):
lps=[0]*len(pattern)
i=1
lenPat=0
while i<len(pattern):
if pattern[i]==pattern[lenPat]:
lenPat+=1
lps[i]=lenPat
i+=1
else:
if lenPat!=0:
lenPat=lps[lenPat-1]
else:
lps[i]=0
i+=1
return lps

print(kmp("helloworld","hello"))
print(kmp("helloworld","hop"))
print(kmp("ABABDABACDABABCABAB","ABABCABAB"))
```


## C) Z Algorithm

### JavaScript Implementation
Expand Down