使用堆栈在python中进行括号匹配

ZENG LINLIN _

我正在尝试使用堆栈来检查括号,但是以下代码无法输出正确的结果;经过几次检查后,我仍然找不到错误;任何提示或帮助,不胜感激!谢谢!

open_list = ["[","{","("] 
close_list = ["]","}",")"] 
def check(mystr):
    stack1 = []
    for i in mystr:
        if i in open_list:
            stack1.append(i)
        elif i in close_list:
            stack1.append(i)
    for i in stack1:
        index1 = open_list.index(i)
        expected_result = close_list[index1]
        if expected_result == stack1[-1]:
            stack1.remove(i)
            stack1.pop(-1)
        else:
            print(i)
            print(stack1, stack1, sep = '\n')
            return 'unbalanced'
    if len(stack1) == 0:
        return 'balanced'
    else:
        print(stack1)
        return 'unbalanced'
# example
list1 = '{a + [b - (c * [e / f] + g) - h] * i}'

# output
(
['[', '(', '[', ']', ')', ']']
['[', '(', '[', ']', ')', ']']
unbalanced
米格尔·阿尔蒙特

修改要迭代的列表将导致跳过元素,在check函数中第二个循环的第一次迭代中,您将具有expected_result== stack1[-1],但是在第二次迭代i中,列表中的第二个值将被修改。 '(' 代替 '['。

您可以通过仅将打开符号添加到堆栈中来简化逻辑,并且每次找到一个关闭符号时都要进行比较,以比较上一次保存的打开符号是否是成对的,如果不是,则是不平衡的。

def check(mystr):
    stack1 = []
    for i in mystr:
        if i in open_list:
            stack1.append(i)
        elif i in close_list:
            if not stack1 or stack1[-1] != open_list[close_list.index(i)]:
                return 'unbalanced'
            else:
                stack1.pop(-1)
    if len(stack1) == 0:
        return 'balanced'
    else:
        print(stack1)
        return 'unbalanced'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章