Skip to content

Commit d0edca5

Browse files
authored
added balanced parentheses in python
1 parent 896f0ee commit d0edca5

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

balanced parentheses.py

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

0 commit comments

Comments
 (0)