Skip to content

Commit 2651234

Browse files
committed
Added optimized code for checking balanced paranthesis in python3
1 parent 2eb0596 commit 2651234

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Optimized Python3 code to Check for balanced parentheses in an expression
2+
open_list = ["[","{","("]
3+
close_list = ["]","}",")"]
4+
5+
# Function to check parentheses
6+
def check(myStr):
7+
stack = []
8+
for i in myStr:
9+
if i in open_list:
10+
stack.append(i)
11+
elif i in close_list:
12+
pos = close_list.index(i)
13+
if ((len(stack) > 0) and
14+
(open_list[pos] == stack[len(stack)-1])):
15+
stack.pop()
16+
else:
17+
return "Unbalanced"
18+
if len(stack) == 0:
19+
return "Balanced"
20+
21+
# Driver code
22+
string = "{[]{()}}"
23+
print(string,"-", check(string))
24+
25+
string = "[{}{})(]"
26+
print(string,"-", check(string))

0 commit comments

Comments
 (0)