Friday, May 26, 2017

Brackets parsing using a stack implementation


Here is a classic brackets parsing problem. In this case we treat []{}()<> are treated as opening and closing brackets accordingly. Now the idea is to insert any bracket into a stack and pop it when we parse a closing bracket and then check whether the popped character is a corresponding opening bracket.

Here is the implementation below :

def checkBrackets(str):
list = []
for c in str:
if c in "<([{":
list.append(c)
if c in ">)]}":
if len(list) == 0:
return 0
popped = list.pop()
if c == ">":
if popped != "<":
return 0
if c == ")":
if popped != "(":
return 0
if c == "]":
if popped != "[":
return 0
if c == "}":
if popped != "{":
return 0
print list
if len(list)==0:
return 1
else:
return 0
print checkBrackets(")")