Two Ways To Check If Paired-Use Symbols Are Closed

检查括号是否闭合的两种方式。

Today let's continue our exploration of Python, we have a new question in checking the matching of paired-use symbols.

Look at the following code block. We need declare a variable marks. If you only use English (with no other characters outside of ASCII on your computer), you may only need the first eight symbols.

marks = "()[]{}<>()【】《》『』「」“”"

The first implementation plan is originally created by me. It adopts loop replacements. Since there must be one or more closed paired-use symbols in the clear text (string passing the filter operation in code line 2), they are simply replaced with empty text. If the final text is empty, the answer is yes; otherwise, it's no.

def loop_replace(string: str):
    string = ''.join(list(filter(lambda x: x in marks, string)))
    pairs = [marks[i:i + 2] for i in range(0, len(marks), 2)]
    length = len(string)  # Record length of string

    while length:
        for pair in pairs:
            string = string.replace(pair, '')

        if len(string) == length:
            # If the length of the string at this iteration of the loop is equal to its length at the
            # last iteration, it means that the replacement cannot match any more closed symbols, so return False.
            return False
        else:
            length = len(string)
    else:
        return True

The next implementation is most useful and most efficient. The first step is same as above: filter out invalid characters and retain brackets signs. Then it declare a temporary variable temp to receive letter one by one in the string, if target is a left sign, append it to the temp; if not, check whether it matched with the last digit of temp, delete the last digit of temp if the checking passed, otherwise directly return False. After iterate overed, return the boolean value of not temp, which means the length of temp should be zero.

def match_in_sequence(string: str):
    lefts, rights = marks[0::2], marks[1::2]
    string = ''.join(list(filter(lambda x: x in marks, string)))
    temp = ''

    for i in string:
        if i in lefts:
            temp += i
        else:
            if temp[-1] == lefts[rights.index(i)]:
                temp = temp[:-1]
            else:
                return False

    return not temp
阅读剩余
THE END