Skip to content

Instantly share code, notes, and snippets.

@hoanbka
Created October 29, 2017 10:40
Show Gist options
  • Save hoanbka/1d4f5f6cc76b715888ccc1d12e3e7f2b to your computer and use it in GitHub Desktop.
Save hoanbka/1d4f5f6cc76b715888ccc1d12e3e7f2b to your computer and use it in GitHub Desktop.
check a balanced Parenthesis
# (){}[]
def isBalancedParenthesis(str):
stack = []
for i in str:
if i == '(' or i == '{' or i == '[':
stack.append(i)
elif i == ')' or i == '}' or i == ']':
if len(stack) == 0:
return False
else:
if stack[-1] == '(' and i == ')' or stack[-1] == '{' and i == '}' or stack[-1] == '[' and i == ']':
stack.pop()
if len(stack) == 0:
return True
else:
return False
# TEST
str = '()(){}[{()}]'
str2 = '[(a+b)*c] - (d+c)*{b*9}'
print(isBalancedParenthesis(str))
print(isBalancedParenthesis(str2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment