Python 用于检查方程式平衡括号的程序

Python 用于检查方程式平衡括号的程序,python,python-3.x,stack,logic,Python,Python 3.x,Stack,Logic,我正试图写一个程序来检查平衡括号中的方程,我的程序正在检查括号,但它只寻找括号,只给出括号的正确答案,但方程的不同答案 我的预期产出是 exp1 = "(2+3)+(1-5)" # True exp2 = "((3*2))*(7/3))" # False exp3 = "(3*5))]" # False 我的计划如下: def is_valid(myStr): """ Check the orders

我正试图写一个程序来检查平衡括号中的方程,我的程序正在检查括号,但它只寻找括号,只给出括号的正确答案,但方程的不同答案

我的预期产出是

exp1 = "(2+3)+(1-5)" # True
exp2 = "((3*2))*(7/3))" # False
exp3 = "(3*5))]" # False
我的计划如下:

def is_valid(myStr):
  """ Check the orders of the brackets
      Returns True or False
  """
  opening = ['(', '[', '{']
  closing = [')', ']', '}']
  stack = []
  for i in myStr:
    if i in opening:
        stack.append(i)
    elif i in closing:
        pos = closing.index(i)
        if ((len(stack) > 0) and
            (opening[pos] == stack[len(stack)-1])):
            stack.pop()
        else:
            return False
    if len(stack) == 0:
        return True
    else:
        return False
  return 

我的程序对上述所有等式返回False,我哪里做错了。

发现了一些错误和改进

PS:最好不要使用i,j作为变量,而是使用一些有意义的名称,如ele,element等

def is_valid(myStr):
    """ Check the orders of the brackets
      Returns True or False
  """
    opening = ['(', '[', '{']
    closing = [')', ']', '}']
    stack = []
    for i in myStr:
        if i in opening:
            stack.append(i)
        elif i in closing:
            pos = closing.index(i)
            if ((len(stack) > 0) and
                    (opening[pos] == stack[-1])):
                stack.pop()
            else:
                stack.append(i)
        else:
            pass
    if len(stack) == 0:
        return True
    else:
        return False


print(is_valid('(2+3)+(1-5)'))
print(is_valid('((3*2))*(7/3))'))
print(is_valid('(3*5))]'))
# True
# False
# False

程序中检查堆栈长度是否为0的最后一个if-else语句应该在for循环之外。我已经更改了代码供您参考,并用您的示例进行了检查。它工作得很好

def is_valid(myStr):
opening = ['(', '[', '{']
closing = [')', ']', '}']

stack = []
for i in myStr:
    if i in opening:
        stack.append(i)
        print(stack)
    elif i in closing:
        pos = closing.index(i)
        if ((len(stack) > 0) and
            (opening[pos] == stack[len(stack)-1])):
            stack.pop()
        else:
            return False
if len(stack) == 0:
    return True
else:
    return False

最后一个if-else条件需要在for循环之外。