Skip to content

Instantly share code, notes, and snippets.

@ankona
Last active October 1, 2021 20:56
Show Gist options
  • Save ankona/5e9f9532efb487814505a4b04d55e091 to your computer and use it in GitHub Desktop.
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
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