【问题标题】:Checking validity of an expression that contains nested parentheses by using stack使用堆栈检查包含嵌套括号的表达式的有效性
【发布时间】:2022-01-10 03:14:30
【问题描述】:

我想使用堆栈来检查包含嵌套括号的表达式的有效性。 我写了下面的代码,但是当我的输入是 [{[]} 时,代码不会返回任何内容,但我希望返回“左括号多于右括号”。 同样当我的输入是()时,响应而不是“平衡”是“不匹配”! 我写的代码有什么错误?

class Stack:       
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, data):
        self.items.append(data)
        return

    def pop(self):
        self.items.pop()

def match(left, right):
    if left == '[' and right == ']':
        return True
    elif left == '{' and right == '}':
        return True
    elif left == '(' and right == ')':
        return True
    else:
        return False

def validity(text):
    st = Stack()

    for i in text:
        if i in '[{(':
            st.push(i)
        if i in ']})':
            if st.is_empty():
                print('right parentheses is more than left one')
                return False
            else:
                compare = st.pop()
                if not match(compare, i):
                    print('mismatched')
                    return False

    if st.is_empty():
        print('balanced')
    else:
        print('left parentheses are more than right ones')

for j in range(4):
    example = input('plz enter text ')
    validity(example)

【问题讨论】:

  • 你的validity 函数不是很连贯:有时它返回一个布尔值,有时它打印一些东西。你应该澄清这一点。

标签: python stack


【解决方案1】:

st.pop() 不返回任何内容,因此比较始终为None

def pop(self):
    return self.items.pop()

应该修复它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2021-10-06
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 2021-07-30
    • 2017-09-12
    • 2022-01-07
    相关资源
    最近更新 更多