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 ..


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.

#@Author :rvashisht

char =[‘D’,’D’]
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..




Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.