在python中使用两个堆栈评估中缀表达式

时间:2014-03-14 04:55:35

标签: python expression infix-notation evaluate

这是我第一次在这里问一个问题,我只是这样做,因为我过去一周都试图弄明白这个问题并且没有能力。我发现了类似的问题,但结果对我没有帮助。我必须使用中缀表达式并使用两个堆栈计算结果,一个用于运算符,一个用于数字。一个例子是6 - ( 5 - 3 ) * ( 4 + 2 ) = -63 * 11 / 8 + 5 – 4 * 7 = -18.875.我无法弄清楚如何让它发挥作用。目前我的代码是:

class NumStack:

    def __init__(self):
        """Create an empty stack."""
        self._data = []                         #nonpublic list instance

    def __len__(self):
        """Return the number of elements in the stack."""
        return len(self._data)

    def is_empty(self):
        """Return True if the stack is empty."""
        return len(self._data) == 0

    def push(self,e):
        """Add element e to the top of the stack."""
        self._data.append(e)                    #new item stored at end of list
        print(self._data)

    def top(self):
        """Return (but do not remove) the element at the top of the stack.

        Raise Empty exception if the stack is empty"""

        if self.is_empty():
            return
        return self._data[-1]                   #the last item in the list

    def pop(self):
        """Remove and return the element from the top of the stack (i.e, LIFO)

        Raise Empty exception if the stack is empty."""

        if self.is_empty():
            return "empty"
        return self._data.pop()                 #remove last item from list

    def str(self):
        return self._data

class OperatorStack:

    def __init__(self):
        """Create an empty stack."""
        self._data = []                         #nonpublic list instance

    def __len__(self):
        """Return the number of elements in the stack."""
        return len(self._data)

    def is_empty(self):
        """Return True if the stack is empty."""
        length = len(self._data)
        if length == 0:
            return True
        else:
            return False


    def push(self,e):
        """Add element e to the top of the stack."""
        self._data.append(e)                    #new item stored at end of list
        print(self._data)

    def top(self):
        """Return (but do not remove) the element at the top of the stack.

        Raise Empty exception if the stack is empty"""

        if self.is_empty():
            return
        return self._data[-1]                   #the last item in the list

    def pop(self):
        """Remove and return the element from the top of the stack (i.e, LIFO)

        Raise Empty exception if the stack is empty."""

        length = len(self)
        if length == 0:
            print("list is empty")
        else:

            if self.is_empty():
                return
            return self._data.pop()

    def str(self):
        return self._data



def main():
    expression = str(input("Enter an expression: "))
    expression = expression.split()
    print(expression)
    N = NumStack()
    O = OperatorStack()   
    new = []
    NewOP = []
    NewNum = [0,0]




    for e in expression:
        if e == '(' or e == ')' or e == '+' or e == '-' or e == '*' or e == '/':
            O.push(e)
        else:
            N.push(e)

    while O.is_empty() == False or N.is_empty() == False:


        TmpOp = O.top()
        if TmpOp == ')':
            O.pop()
        elif TmpOp == '(':
            O.pop()
        if TmpOp != '(' and TmpOp != ')':
            new.append(N.pop())
            new.append(O.pop())

        print(TmpOp)

        while TmpOp == ')':

            if N.top() != "empty":
                NewNum[1] = N.pop()
            if N.top() != "empty":
                NewNum[0] = N.top()
                print(NewNum[0],NewNum[1])

            if O.pop() == '+':
                num = float(NewNum[1]) + float(NewNum[0])
                new.append(num)
                print(num)
                O.pop()
                break



            elif O.pop() == '-':
                num = float(NewNum[0]) - float(NewNum[1])
                new.append(num)
                print(num)
                O.pop()
                break



            elif O.pop() == '*':
                num = NewNum[1]*NewNum[0]
                new.append(num)
                print(num)
                # O.pop()
                break



            elif O.pop() == '/':
                num = NewNum[1]/NewNum[0]
                new.append(num)
                print(num)
                #  O.pop()
                break



            if O.top() == ')':
                O.pop()
                break

            if O.__len__() == 0 and N.__len__() == 0:
                break
        continue
        while TmpOp != ')' and TmpOp != '(':
            new.append(N.pop())
            new.append(O.pop())
            print(new)

            if O.__len__() == 0 and N.__len__() == 0:
                break


        print(new)





main()

我相信我的课程是正确的,我只是找不到正确提取所需信息的方法。我正在尝试将项目弹出到列表中,当我到达括号时,我继续执行计算。如果我可以在我的列表中找到正确的数字,那么我知道我可以让它工作。我只需要获得" new"包含正确的数字。遇到问题:"6 - ( 5 - 3 ) * ( 4 + 2 )"我应该[6.0, '*', 2.0, '-', 6]。它没有出来。我非常感谢能给予的任何帮助。

0 个答案:

没有答案