Skip to content

Instantly share code, notes, and snippets.

@realFranco
Created November 9, 2021 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realFranco/59de9737e2c92e38f8fe3180bed3da60 to your computer and use it in GitHub Desktop.
Save realFranco/59de9737e2c92e38f8fe3180bed3da60 to your computer and use it in GitHub Desktop.
String Matcher Algorithm - Naive
"""
November 9th, 2021
Naive Implmementation
Exacution example
> python3 string_match.py
"""
class StringMatch():
text: str
pattern: str
def __init__(self, text: str, pattern: str):
self.text = text
self.pattern = pattern
def naive_string_matcher(text: str, pattern: str) -> int:
n, m = len(text), len(pattern)
for s in range(0, n - m):
if pattern[1:m] == text[s+1:s+m]:
return s
if __name__ == '__main__':
print('[START] Naive String Matcher\n')
tests = [
StringMatch('fresh fried fish', 'sh'),
StringMatch('honda civic ek9', 'ek')
]
for stringMatchCase in tests:
out = naive_string_matcher(stringMatchCase.text, stringMatchCase.pattern)
print(f'Text: "{stringMatchCase.text}"')
print(f'Pattern: "{stringMatchCase.pattern}"')
print(f'El patrón ocurre con desplazamiento: {out}\n')
print('[END] Naive String Matcher')
@realFranco
Copy link
Author

Execution output:

[START] Naive String Matcher

Text: "fresh fried fish"
Pattern: "sh"
El patrón ocurre con desplazamiento: 3

Text: "honda civic ek9"
Pattern: "ek"
El patrón ocurre con desplazamiento: 12

[END] Naive String Matcher

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment