我想在python中制作一个括号检查器来计算错误的括号

2024-09-30 16:33:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编一个括号检查器程序。但我想让它数一数不匹配的括号。我在用python。在这个问题上我怎么用stack呢?你知道吗

我试过一些代码,但没有成功,因为它不能计算错误的括号。你知道吗

if __name__ == "__main__":
    # text = sys.stdin.read()
    text = str(input())
    stackie = []
    num = 0
    opening_brackets_stack = []
    for i, next in enumerate(text):
        if next == '(' or next == '[' or next == '{':
            # Process opening bracket, write your code here
            stackie.append(next)
            pass

        if next == ')' or next == ']' or next == '}':
            # Process closing bracket, write your code here
            if next == ")" :
                if '(' in stackie :
                    stackie.remove("(")
                else:
                    num += 1
            if next == "]" :
                if '[' in stackie :
                    stackie.remove("[")
                else:
                    num += 1
            if next == "}" :
                if '{' in stackie :
                    stackie.remove("{")
                else:
                    num += 1
            pass

Tags: ortextinifstackprocesselsenum
2条回答

我想如果你想写一个classical bracket parser,逻辑中的一个错误是调用堆栈上的remove,而不是比较pop。你知道吗

要确定它什么时候按预期工作,什么时候不按预期工作并不容易,所以一些测试用例和它们的预期行为有很大的帮助,比如说,对于'(asd(gdgd)[dfdf])''[(asd(gdgd)[dfdf])''(asd(gdg{d)[df}df])',您希望得到什么作为输出?你知道吗

以这段代码为例:

BRACKET_MATCHES = {')': '(', ']': '[', '}': '{'}

def bracket_check(text):
    stack = []
    for n, char in enumerate(text):
        if char in '([{':
            stack.append((char, n))
        if char in ')]}':
            match = stack.pop()
            if match[0] != BRACKET_MATCHES[char]:
                print(f"Can't match bracket '{char}' at {n}, "
                      f"conflicting with '{match[0]}' at {match[1]}.")
                return False
    if len(stack) != 0:
        print(f"Open brackets remaining at positions: "
              f"{' '.join(map(str, stack))}")
        return False
    return True

根据之前的样本,我们得到:

>>> bracket_check('(asd(gdgd)[dfdf])')
True
>>> bracket_check('(asd(gdg{d)[df}df])')
"Can't match bracket ')' at 10, conflicting with '{' at 8."
False
>>> bracket_check('[(asd(gdgd)[dfdf])')
"Open brackets remaining at positions: ('[', 0)"
False

这个解决方案停留在第一个不匹配的括号上,主要是因为这个问题比以人类的方式找到所有不匹配的括号要容易得多。后者在规则大小的文本中计算起来相当复杂,仍然不能确定是否能给出所需的结果。你知道吗

除非这是绝对不可行的,否则在我看来,通过修复括号错误来迭代工作是更可取的。你知道吗

我附上了下面的解决方案,希望它是自我描述,将做你想要的。你知道吗

def check_closed_brackets(open_bracket, nonclosed_opening_brackets, nonopened_closing_brackets):
    if len(nonclosed_opening_brackets) == 0: # There are no opened brackets remaining so the close must be invalid
        nonopened_closing_brackets.append(element)
    else: # Open brackets exist lets check them
        if element == ")" :
            if nonclosed_opening_brackets[len(nonclosed_opening_brackets) -1] == '(':
                nonclosed_opening_brackets.remove("(")
            else:
                nonopened_closing_brackets.append(element)

        if element == "]" :
            if nonclosed_opening_brackets[len(nonclosed_opening_brackets) -1] == '[':
                nonclosed_opening_brackets.remove("[")
            else:
                nonopened_closing_brackets.append(element)

        if element == "}" :
            if nonclosed_opening_brackets[len(nonclosed_opening_brackets) -1] == '{':
                nonclosed_opening_brackets.remove("{")
            else:
                nonopened_closing_brackets.append(element)

if __name__ == "__main__":
    # text = sys.stdin.read()
    text = str(input())
    nonclosed_opening_brackets = []
    nonopened_closing_brackets = []
    for i, element in enumerate(text):
        if element == '(' or element == '[' or element == '{':
            nonclosed_opening_brackets.append(element)

        if element == ')' or element == ']' or element == '}':
            check_closed_brackets(element, nonclosed_opening_brackets, nonopened_closing_brackets)

    print('Number of Opened Brackets that are not closed: {0}'.format(len(nonclosed_opening_brackets)))
    print('Number of Closed Brackets that are not opened: {0}'.format(len(nonopened_closing_brackets)))

相关问题 更多 >