Skip to content

Instantly share code, notes, and snippets.

@thetongs
Created December 5, 2020 05:48
Show Gist options
  • Save thetongs/b66bb4a8d5ed67eb11877bc8f672b2ae to your computer and use it in GitHub Desktop.
Save thetongs/b66bb4a8d5ed67eb11877bc8f672b2ae to your computer and use it in GitHub Desktop.
## Balance parenthesis check
#
def checker(s):
# Check length
if(len(s) % 2 != 0):
return False
# set of opening brackets
opening = set('([{')
# set of matching pair
matches = set([ ('(',')'), ('[', ']'), ('{', '}')])
# stack
stack = []
# Check parenthesis
for paren in s:
if paren in opening:
stack.append(paren)
else:
if len(stack) == 0:
return False
last_open = stack.pop()
if(last_open, paren) not in matches:
return False
return len(stack) == 0
# Feed
pa = '[]'
result = checker(pa)
print("{} - {}".format(pa, result))
pa = '[]['
result = checker(pa)
print("{} - {}".format(pa, result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment