Skip to content

Commit f8b9345

Browse files
authored
Merge pull request prabhupant#67 from braceritchie/master
Determine if an expression is balanced using stack
2 parents 13b8347 + 42bf0b4 commit f8b9345

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# simple program to check if an expression is balanced using stack
2+
stack = []
3+
def checkBalanced(expr):
4+
for i in expr:
5+
if i == "{" or i == "[" or i == "(":
6+
stack.append(i)
7+
elif i == "}" or i == "]" or i == ")":
8+
temp = stack.pop()
9+
if i == "}" and temp != "{":
10+
return False
11+
elif i == "]" and temp != "[":
12+
return False
13+
elif i == ")" and temp != "(":
14+
return False
15+
16+
return True
17+
18+
# main function
19+
expr = input()
20+
result = checkBalanced(expr)
21+
if result:
22+
print("Expression is balanced")
23+
else:
24+
print("Expression is not balanced")

0 commit comments

Comments
 (0)