Pattern search in String using Python

For fun I just thought about writing an algorithm on using pattern search in any given string using python, Lets assume you have a string with a value of “SSDDFFEERRTTYYSS” and a character array [‘D’,’D’], Now use the values of character array as a pattern and search for the maximum character occurrence of match in the string value. in plain words, we have a ..

value : “SSDDFFEERRTTDDDSS

pattern : [‘D’,’D’] i.e DD

Expected output is :3 (as DD pattern appears thrice [XXDDXXXXXDDDXXX).

Also assume the Char array can be dynamic, I mean could be of any limit of characters.

#!/usr/bin/python
#@Author :rvashisht

char =[‘D’,’D’]
string = “SSDDFFEERRTTDDDSS”
count = 0

i =0
j = 0
pattern = ”
charLength = len(char) # get the length of char array
for i in range(len(char)):
pattern += char[i]

for j in range(len(string)-1):
#extract the chars from string, it should match char pattern length
chars = string[ j : j+charLength] #search in string with pattern
if pattern == chars : #check if pattern match
print chars, “=”, pattern
count = count +1 # increase the counter

print “Total occurrence of pattern found”, count

Well this is just a try.. Please review and comment..

Cheers!

Thanks

RVashi

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s