Skip to content

Instantly share code, notes, and snippets.

@NimaBavari
Last active February 23, 2023 20:32
Show Gist options
  • Save NimaBavari/58c6ba0fbab077daa7a44f963049587e to your computer and use it in GitHub Desktop.
Save NimaBavari/58c6ba0fbab077daa7a44f963049587e to your computer and use it in GitHub Desktop.
Parses a pattern and checks if the given string matches that pattern
def is_matching(cand):
"""Parses a composite `cand` and check if the string matches
the pattern. E.g.,
cand = "++$*+*{2} xm4cccdvv" -> True.
`cand` is a pattern and a string separated by a space. Each "+"
in the pattern means an alphabetic character in the string; each
"$" means a numeric character (1-9); each "*" means an alphabetic
character repeated N times with N >= 1 if it is followed by "{N}"
and otherwise an alphabetic character repeated 3 times.
"""
pattern, s = cand.split()
p_idx, s_idx = 0, 0
while p_idx < len(pattern) and s_idx < len(s):
if pattern[p_idx] == "+":
if not s[s_idx].isalpha():
return False
p_idx += 1
s_idx += 1
elif pattern[p_idx] == "$":
if not s[s_idx].isnumeric():
return False
p_idx += 1
s_idx += 1
elif pattern[p_idx] == "*":
if pattern[p_idx + 1] == "{":
closing_pos = p_idx + pattern[p_idx:].index("}")
num = int(pattern[p_idx + 2 : closing_pos])
p_idx = closing_pos + 1
else:
num = 3
p_idx += 1
repeating_part = s[s_idx: s_idx + num]
if not repeating_part.isalpha() or repeating_part != repeating_part[0] * num:
return False
s_idx += num
if p_idx != len(pattern) or s_idx != len(s):
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment