File tree Expand file tree Collapse file tree 1 file changed +16
-10
lines changed Expand file tree Collapse file tree 1 file changed +16
-10
lines changed Original file line number Diff line number Diff line change 1
- # simple program to check if an expression is balanced using stack
2
1
stack = []
3
2
def checkBalanced (expr ):
4
3
for i in expr :
5
4
if i == "{" or i == "[" or i == "(" :
6
5
stack .append (i )
7
6
elif i == "}" or i == "]" or i == ")" :
8
- temp = stack .pop ()
9
- if i == "}" and temp != "{" :
7
+ if not stack :
10
8
return False
11
- elif i == "]" and temp != "[" :
9
+ top = stack .pop ()
10
+ if i == "}" and top != "{" :
12
11
return False
13
- elif i == ") " and temp != "( " :
12
+ elif i == "] " and top != "[ " :
14
13
return False
14
+ elif i == ")" and top != "(" :
15
+ return False
16
+ else :
17
+ print ("Invalid Expression" )
18
+ return False
15
19
16
- return True
20
+ if not len (stack ):
21
+ return True
22
+ else :
23
+ return False
17
24
18
25
# main function
19
26
expr = input ()
20
- result = checkBalanced (expr )
21
- if result :
22
- print ("Expression is balanced" )
27
+ if not checkBalanced (expr ):
28
+ print ("Not Balanced" )
23
29
else :
24
- print ("Expression is not balanced" )
30
+ print ('Balanced' )
You can’t perform that action at this time.
0 commit comments