Created
May 15, 2019 18:59
-
-
Save Sukhrobjon/6f05f397e2b63b10314fb8594a5659c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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