这个平衡的paren问题怎么了?没有结果也没有错误

问题描述 投票:0回答:1

我没有收到任何错误或任何结果,因此我无法确切指出问题所在。它基于“堆栈”数据结构。

def is_match(p1, p2):
    return (p1,p2) in ['(,)', '{,}', '[,]']

def is_open(param):
    return param in '([{'

def is_balanced(exp):
    stack = []
    for i in range(len(exp)):
        if is_open(exp[i]):
            stack.append(exp[i])
        else:
            top = stack.pop()
            if not is_match(top,str(exp[i])):
                return False

    if stack == []:
        return True
    else:
        return False


is_balanced('{[}')
python stack structure
1个回答
1
投票

首先,您没有打印任何内容。您的函数始终返回False,但不返回print,结果将被丢弃。

第二,您遇到逻辑错误。最明显的是('(', ')')从不等于'(,)'。而且,如果您在弹出时不测试堆栈是否为空,那么在输入诸如'}'的情况下,您将得到一个错误。 str(exp[i])是多余的,exp[i]已经是一个字符串。最后,

if condition:
    return True
else:
    return False

是反模式;您可以简单地说return condition(或者,如果不是布尔值,并且您希望它是return bool(condition);在这种情况下就不需要,因为相等比较的结果始终是布尔值)。

© www.soinside.com 2019 - 2024. All rights reserved.