【问题标题】:parenthesis matching in python using stack使用堆栈在python中匹配括号
【发布时间】:2021-02-13 05:09:19
【问题描述】:

我正在尝试使用堆栈检查括号,但以下代码无法输出正确的结果;查了好几遍,还是找不到错误;非常感谢任何提示或帮助!谢谢!

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

【问题讨论】:

  • 注意——列表不是堆栈。如果你不调用像 .remove(i) 这样的函数,它们只是堆栈,它从前面遍历列表并删除对象 i 的第一个匹配项(不是索引,i 是这里是一个字符串,因此 var 名称可能会让您感到困惑)。 index(i) 也从前面遍历,不能保证给你你可能期望的索引。如果您希望列表中的每个项目都有一个索引元素对,请使用 enumerate。此外,在迭代列表时不要修改列表,这会跳过元素。
  • 您遍历列表并更改它。最好不要那样做。导致非常混乱的逻辑。改用while len(stack1): 并继续检查列表的第一个和最后一个。
  • 好的;我已经改变了一段时间;但为什么我不能在堆栈中使用 remove(i) ?你的意思是在堆栈中,我们只能使用索引?

标签: python stack singly-linked-list


【解决方案1】:

修改您正在迭代的列表将导致跳过元素,在检查函数的第二个循环的第一次迭代中,您将拥有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'

【讨论】:

  • 谢谢!这更简洁明了!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多