Wednesday, November 11, 2015

Check if Expression is Balanced or Not using Stack in Python

import re
balance1 ='2+4-5+[(7+8)-[]]'
balance=list(balance1)
stack=[]
flag=1;

for x in balance:
if re.match('[\(\[\{]',x):
stack.append(x)
else:
if re.match('\)\}\]',x) and stack==[]:
flag=0
break
elif stack!=[]:
if x==')'and stack.pop()!='(':
flag=0
break
if x=='}'and stack.pop()!='{':
flag=0
break
if x==']'and stack.pop()!='[':
flag=0
break
if flag:
print("balanced")
else:
print("Not balanced")

No comments:

Post a Comment

Contributors

Translate