Last active
October 1, 2021 20:56
-
-
Save ankona/5e9f9532efb487814505a4b04d55e091 to your computer and use it in GitHub Desktop.
Determine if the special characters in the incoming string are valid parenthetical expressions
This file contains 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 is_valid(s: str) -> bool: | |
""" | |
Determine if the special characters in the incoming string are valid parenthetical expressions | |
:param s: | |
:return: | |
""" | |
# ( [ ( ) ] | |
brackets_q = [] | |
spec_lhs, spec_rhs = ['(', '{', '['], [')', '}', ']'] | |
for c in s: | |
if c in spec_lhs: # F | |
brackets_q.append(c) # ( [X (X | |
if c in spec_rhs: # F F F T) T | |
if not len(brackets_q): | |
return False | |
last_bracket = brackets_q.pop() # ( [ | |
idx_match = spec_lhs.index(last_bracket) # 0 2 | |
if c != spec_rhs[idx_match]: # F F | |
return False | |
if len(brackets_q): # T - ( remains | |
return False | |
return True | |
if __name__ == '__main__': | |
x = is_valid("(]") | |
print('isvalid:', x) | |
x = is_valid("()") | |
print('isvalid:', x) | |
x = is_valid("([)") | |
print('isvalid:', x) | |
x = is_valid("([])") | |
print('isvalid:', x) | |
x = is_valid("([]{})") | |
print('isvalid:', x) | |
x = is_valid("( [ ( ) ]") | |
print('isvalid:', x) | |
x = is_valid("{{{{{{{{{{{{{{{( [ ( ) ] )}}}}}}}}}}}}}}}") | |
print('isvalid:', x) | |
x = is_valid("{{{{{{{{{{{{{{{( [ ( ) ] )}}} ] }}}}}}}}}}}}") | |
print('isvalid:', x) | |
x = is_valid("{}[]{}[]{}[]{}[]{}[]{}[]") | |
print('isvalid:', x) | |
x = is_valid("({}[])[{}[]]((({}[]{}[]{}[]{}[])))") | |
print('isvalid:', x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment