使用堆栈评估中缀表达式

时间:2017-09-15 05:48:57

标签: python python-3.x stack infix-notation

所以我目前正在学习后缀,前缀和中缀表达式;其中一个挑战问题是使用堆栈评估中缀表达式。我想我理解它的概念。但是,我真的很困惑为什么我的操作员没有推进我的堆栈。我相信问题在第31行。但是,我不确定为什么。有人可以帮我找到并解决问题吗?

class Stack:

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

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

    def push(self, item):
        self.items.append(item)

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

    def peek(self):
        return self.items[len(self.items) - 1]

    def size(self):
        return len(self.items)

    def infix(equation):
        prec_dictionary = {"(": 0, ")": 0, "^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "<": 1, ">": 1} 
        operator_stack = Stack()
        operand_stack = Stack()
        allowed_operators = "+-/*^<>"
        a_list = equation.split()
        for i in a_list:
            if i in allowed_operators:
                if operator_stack.is_empty():
                    operator_stack.push(i)
                else:
                    if prec_dictionary[i] > prec_dictionary[operator_stack.peek()]:
                        operator_stack.push(i)
            if i == "(":
                operator_stack.push(i)
            elif i == ")":
                while operator_stack.peek() != "(":
                    value1 = int(operand_stack.pop())
                    operator = operator_stack.pop()
                    value2 = int(operand_stack.pop())
                    value = compute(value1, value2, operator)
                    operand_stack.push(value)
                operator_stack.pop()
            else:
                operand_stack.push(i)
        return operand_stack.pop()

    def compute(number1, number2, operator):
        if operator == "+":
            return number1 + number2
        elif operator == "-":
            return number1 - number2
        elif operator == "*":
            return number1 * number2
        elif operator == "/":
            return number1 / number2
        elif operator == "^":
           return number1 ** number2
        elif operator == "<":
            return min(number1, number2)
        else:
            return max(number1, number2)    

    print(infix('2 ^ ( 1 + 3 ^ 2 )'))

0 个答案:

没有答案