Python program to check matching of simple parentheses

后端 未结 25 2399
谎友^
谎友^ 2020-12-01 17:02

I am a Python newbie and I came across this exercise of checking whether or not the simple brackets \"(\", \")\" in a given string are matched evenly.

I have seen ex

25条回答
  •  悲哀的现实
    2020-12-01 17:38

    An alternative to check for balanced nested parentheses:

    def is_balanced(query: str) -> bool:
        # Alternative: re.sub(r"[^()]", "", query)
        query = "".join(i for i in query if i in {"(", ")"})
        while "()" in query:
            query = query.replace("()", "")
        return not query
    
    
    for stmt in [
        "(()()()())",    # True
        "(((())))",      # True
        "(()((())()))",  # True
        "((((((())",     # False
        "()))",          # False
        "(()()))(()",    # False
        "foo",           # True
        "a or (b and (c or d)",  # False
        "a or (b and (c or d))"  # True
        "a or (b and (c or (d and e)))",  # True
    ]:
        print(stmt)
        print("Balanced:", is_balanced(stmt))
        print()
    

    It works by:

    1. Removing everything but parentheses
    2. Recursively remove innermost parentheses pairs
    3. If you're left with anything besides the empty string, the statement is not balanced. Otherwise, it is.

提交回复
热议问题