Skip to content

Commit 18616c7

Browse files
authored
Merge pull request #723 from sravanyabendi/parenthesis
Python code to Check for balanced parentheses in an expression
2 parents f9fd5c6 + 8d51b76 commit 18616c7

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
## Python code to Check for
2+
# balanced parentheses in an expression
3+
4+
5+
#Function to check parentheses
6+
def validparentheses(s):
7+
open_brace=["{","[","("]
8+
closed_brace=["}","]",")"]
9+
stack=[]
10+
for i in s:
11+
if i in open_brace:
12+
stack.append(i)
13+
elif i in closed_brace:
14+
p=closed_brace.index(i)
15+
if len(stack)>0 and open_brace[p]==stack[len(stack)-1]:
16+
stack.pop()
17+
else:
18+
return False
19+
if(len(stack)==0): #return true if given expression is balanced
20+
return True
21+
else:
22+
return False #return false is not balanced
23+
24+
s=input("Enter the Expression to be evaluated:")
25+
if(validparentheses(s)):
26+
print("Expression is Balanced")
27+
else:
28+
print("Expression is Unbalanced")

0 commit comments

Comments
 (0)