Skip to content

Instantly share code, notes, and snippets.

@iJustErikk
Created November 24, 2020 19:02
Show Gist options
  • Save iJustErikk/9b0282b660bdf57f80d635b2f5949182 to your computer and use it in GitHub Desktop.
Save iJustErikk/9b0282b660bdf57f80d635b2f5949182 to your computer and use it in GitHub Desktop.
Naive Substring Algorithm
def indexOf(text, string):
for i in range(len(text)):
didBreak = False
for j in range(len(string)):
if (i+j >= len(text)):
didBreak = True
break
if (text[i + j] != string[j]):
didBreak = True
break
if (not didBreak): return i
return -1
# should work if not in there at all
assert(indexOf("Interested in writing your own Python scenarios and demos?", "z") == -1)
# should work if substring bigger than string
assert(indexOf("z", "Interested in writing your own Python scenarios and demos?") == -1)
# should work normally
assert(indexOf("Interested in writing your own Python scenarios and demos?", "in") == 11)
# should work if it is the ending part of string or partially found
assert(indexOf("Interested in writing your own Python scenarios and demos?", "mos?.") == -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment