Stacks are often used for parsing. A simple parsing task is to check whether a string of parentheses are matching.
For example, the string ([])
is matching, because the outer and inner brackets form pairs. ()<>)
is not matching, because the last )
has no partner. ([)]
is also not matching, because pairs must be either entirely inside or outside other pairs.
def checkParenth(str):
stack = Stack()
pushChars, popChars = "<({[", ">)}]"
for c in str:
if c in pushChars:
stack.push(c)
elif c in popChars:
if stack.isEmpty():
return False
else:
stackTop = stack.pop()
# Checks to see whether the opening bracket matches the closing one
balancingBracket = pushChars[popChars.index(c)]
if stackTop != balancingBracket:
return False
else:
return False
return not stack.isEmpty()