Balanced Parentheses

Given an expression string expression, write a program to examine whether the pairs and the orders of {, }, (, ), [, ] are correct in expression.

Source Code:
str1=input()
stack=[]
for i in range(len(str1)):
    if(str1[i]=='(' or str1[i]=='{' or str1[i]=='['):
        stack.append(str1[i])
    elif str1[i]==')' and stack[len(stack)-1]=='(':
        stack.pop()
    elif str1[i]=='}' and stack[len(stack)-1]=='{':
        stack.pop()
    elif str1[i]==']' and stack[len(stack)-1]=='[':
        stack.pop()
    else:
        break
if i==len(str1)-1 and stack==[]:
    print("Balanced")
else:
    print("Not Balanced")

Sample Input1:
[()]{}{[()()]()}
Sample Output1:
Balanced
Sample Input2:
[(])
Sample Output1:
Not Balanced

No comments:

Post a Comment

Total Pageviews