Created
November 26, 2023 22:27
-
-
Save camtheman256/05564ed4b0a4e0c42f671ae8e206d05d to your computer and use it in GitHub Desktop.
Log-space parentheses matcher.
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 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