关闭或打开括号检查器

时间:2017-11-22 04:35:10

标签: python-3.x

我正在尝试编写程序来确定数学表达式是否包含匹配的括号。我需要检查它们是否具有相同数量的左右对比,然后从中确定它们是否打开。但我不知道该怎么做。在我得到表达后,没有任何结果出来。我知道有更好的方法可以找出它们是否已关闭......但我无法弄清楚

他们可以检查的表达式的例子是(5 + 5)/(5 + 2-5),或类似的东西

def main():
  left = 0
  right = 0
  even = (0 or 2 or 4 or 6 or 8 or 10 or 12 or 14) #is there a better way to check if they match rather than doing even or odd?
  odd = (1 or 3 or 5 or 7 or 9 or 11 or 13 or 15)
  if expression == "(": 
    left += 1
  elif expression == ")":
    right -= 1
  expression = input("write a mathematical expression with parentheses") #lets user input mathematical expression to evaluate for correct number of parentheses
  parentheses = (left + right) #this is probably not the most efficient way, I just want to find out if my parentheses match, so suggestions here would help
  if parentheses == even: 
    print("Your parentheses are closed")
  if parentheses == odd:
    print("You are missing a parenthese")




main()

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题:

  1. 您需要迭代输入字符串中的每个字符(expression)以查看它是否为括号或其他字符,然后计算它们。
  2. 在决定是否关闭或打开括号之前,您需要执行 1
  3. 本身不是问题,但您可以使用模运算符%测试某些内容是否均匀,而不是定义偶数和奇数变量。
  4. 您的代码中存在一些效率低下和不必要的变量
  5. 以下代码应该执行您之后的操作:

    def main():
        left = 0
        right = 0
        expression = raw_input("write a mathematical expression with parentheses: ")
        for character in expression:
            if character == '(':
                left = left + 1
            elif character == ')':
                right = right + 1
    
        total = left + right
        if (left < right):
            missing = "left"
        elif (right < left):
            missing = "right"
        if (total % 2) == 0:
            print("Your parentheses are closed")
        else:
            print("You are missing a " + missing + " parentheses")
    
    main()