Skip to content

Commit cbe2097

Browse files
authored
Updated balanced_expression.py to fix bugs
1 parent fafcfab commit cbe2097

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed
Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
1-
# simple program to check if an expression is balanced using stack
21
stack = []
32
def checkBalanced(expr):
43
for i in expr:
54
if i == "{" or i == "[" or i == "(":
65
stack.append(i)
76
elif i == "}" or i == "]" or i == ")":
8-
temp = stack.pop()
9-
if i == "}" and temp != "{":
7+
if not stack:
108
return False
11-
elif i == "]" and temp != "[":
9+
top = stack.pop()
10+
if i == "}" and top != "{":
1211
return False
13-
elif i == ")" and temp != "(":
12+
elif i == "]" and top != "[":
1413
return False
14+
elif i == ")" and top != "(":
15+
return False
16+
else:
17+
print("Invalid Expression")
18+
return False
1519

16-
return True
20+
if not len(stack):
21+
return True
22+
else:
23+
return False
1724

1825
# main function
1926
expr = input()
20-
result = checkBalanced(expr)
21-
if result:
22-
print("Expression is balanced")
27+
if not checkBalanced(expr):
28+
print("Not Balanced")
2329
else:
24-
print("Expression is not balanced")
30+
print('Balanced')

0 commit comments

Comments
 (0)