In: Computer Science
Python: If I am given a string consisting only of parentheses - (, ), {, }, [, and ], how would I write a Boolean function that takes a string and decides if it consists of valid nested parenthesis? One of the hints given was to use stack. For example --> {()[{}]}' is valid.
screenshot
code
def isBalanced(str1):
stk = []
for char in str1:
if char == '(' or char == '{' or char == '[':
stk.append(char)
elif char == ')' or char == '}' or char == ']':
# if stk is empty means unbalanced
if len(stk) <= 0:
return False
elif char == ')':
if stk[len(stk)-1] != '(':
return False
stk.pop()
elif char == '}':
if stk[len(stk)-1] != '{':
return False
stk.pop()
elif char == ']':
if stk[len(stk)-1] != '[':
return False
stk.pop()
# all paranthesis are balanced then stk is empty
if len(stk) != 0:
return False
else:
return True
str1 = "{()[{}]}"
print(isBalanced(str1))