Skip to content

Instantly share code, notes, and snippets.

@camtheman256
Created November 26, 2023 22:27
Show Gist options
  • Save camtheman256/05564ed4b0a4e0c42f671ae8e206d05d to your computer and use it in GitHub Desktop.
Save camtheman256/05564ed4b0a4e0c42f671ae8e206d05d to your computer and use it in GitHub Desktop.
Log-space parentheses matcher.
def parens(s: str):
def parser_paren(i: int) -> tuple[bool, int]:
i += 1
result = True
while i < len(s) and result and s[i] != ")":
if s[i] == "(":
result, i = parser_paren(i)
elif s[i] == "[":
result, i = parser_bracket(i)
else:
return False, 0
if not result:
return False, 0
if i > len(s) - 1:
return False, 0
return True, i+1
def parser_bracket(i: int) -> tuple[bool, int]:
i += 1
result = True
while i < len(s) and result and s[i] != "]":
if s[i] == "(":
result, i = parser_paren(i)
elif s[i] == "[":
result, i = parser_bracket(i)
else:
return False, 0
if not result:
return False, 0
if i > len(s) - 1:
return False, 0
return True, i+1
result, i = True, 0
while i < len(s) and result:
if s[i] == "(":
result, i = parser_paren(i)
else:
result, i = parser_bracket(i)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment