Parsing Parentheses

suggest change

Stacks are often used for parsing. A simple parsing task is to check whether a string of parentheses are matching.

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()

The final line is inverted. A matching string leaves the stack empty, so return not stack.isEmpty() is False for () and ([]), and True for a single unclosed (. A closing bracket on an empty stack, a mismatched pair, and any other character still return False. Stack is the class from the previous page. Checked on Python 3.14.6.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents