-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBalancing parentheses.py
More file actions
34 lines (32 loc) · 991 Bytes
/
Balancing parentheses.py
File metadata and controls
34 lines (32 loc) · 991 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#Write a program to check if a given expression has balanced parentheses.The input string is allowed to contain only three types of brackets: parentheses, i.e. ’(’ / ’)’ , curly braces ’{’ / ’}’ and square brackets ’[’ / ’]’.
#refer: https://www.youtube.com/watch?v=QZOLb0xHB_Q
inp = "([[]])[{}]"
# Your code - begin
opening=['(','[','{']
closing=[')',']','}']
i=0
s=[]
while i<len(inp):
if inp[i] in opening:
s.append(inp[i])
elif inp[i] in closing:
if len(s)==0:
output='NOT BALANCED'
else:
if inp[i]==')' and s[len(s)-1]=='(':
s.pop()
elif inp[i]==']' and s[len(s)-1]=='[':
s.pop()
elif inp[i]=='}' and s[len(s)-1]=='{':
s.pop()
else:
output='NOT BALANCED'
else:
output='INVALID INPUT'
i+=1
if len(s)==0:
output='BALANCED'
else:
output='NOT BALANCED'
# Your code - end
print output