Skip to content

Instantly share code, notes, and snippets.

@Sukhrobjon
Created May 15, 2019 18:59
Show Gist options
  • Save Sukhrobjon/6f05f397e2b63b10314fb8594a5659c6 to your computer and use it in GitHub Desktop.
Save Sukhrobjon/6f05f397e2b63b10314fb8594a5659c6 to your computer and use it in GitHub Desktop.
def find_index(text, pattern):
"""
Return the starting index of the first occurrence of pattern in text,
or None if not found.
"""
# if pattern is empty
if pattern == "":
return 0
starter = 0 # the starting index of the patterin in the text
index = 0 # index for text
subindex = 0 # index for pattern
while index <= len(text) - 1:
if text[index] == pattern[subindex]: # char is mathched
index += 1
subindex +=1
if subindex == len(pattern): # check for if we checked all index of patter
# starter index of the text where pattern occured 1st time
return starter
else: # mismatch found
starter += 1 # shift the starter to next index
index = starter
subindex = 0 # reset the subindex
return None # pattern not found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment