Python使用Stacks问题评估Infix表示法

时间:2014-03-19 16:47:54

标签: python stack infix-notation

我道歉,如果我在这里看起来很蠢,但我很难过......如上所述,我需要让这个程序使用堆栈来评估中缀符号表达式,但我不能在我的生活中让这个东西得到适当的解决。

如果有人可以帮我修改我的代码,并可能解释我哪里出错,那么我会非常感激。此外,抱歉格式不稳定,这是我的第一篇文章,我不完全理解代码输入格式。

import operator

def Main():
    #In main, necessary stacks are generated and 
    #all calculations and methods are called and preformed. 

    opStack = ArrayStack()
    numStack = ArrayStack()
    opList = ['*', '/', '+', '-']
    nums = '1234567890'
    parn = ['(', ')']
    toEval = input('Enter the Expression: ')

    toEval = toEval.split()
    #print(toEval)

    for each in toEval:

        if each in nums:
            numStack.push(each)

        if  each == parn[0]:
            opStack.push(each)

        if each in opList:            
            if each == opList[2] or opList[3]:
                opStack.push(each)

            if each == opList[0] or opList[1]:
                    while opStack.top() == (opList[2] or opList[3]) and len(opStack) > 0 and len(numStack) >= 2:
                        ans = Eval(numStack.pop(),numStack.pop(),opStack.pop())
                        numStack.push(ans)   
                        opStack.push(each)
        if each == parn[1]:
            while opStack.top() != "(":
                ans = Eval(numStack.pop(),numStack.pop(),opStack.pop()) # this line is poping the empty stack
                numStack.push(ans)
            opStack.pop()

    while opStack.is_empty() != True:
        ans = Eval(numStack.pop(),numStack.pop(),opStack.pop())
        numStack.push(ans)
    print(ans)


def Eval(num1, num2, op):
    #two numbers and an op are pulled from stacks, op checked against dict
    #dict should supply necessary 

    ops2 = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}

    op_char = op

    op_func = ops2[op_char]

    res = op_func(float(num1), float(num2))

    return res



class ArrayStack:
# LIFO Stack implementation using a Python list as underlying storage.

    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

    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():
            raise Empty( 'Stack is empty' )
        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():
            raise Empty( 'Stack is empty' )
        return self._data.pop() # remove last item from list



Main()

1 个答案:

答案 0 :(得分:0)

这两个if语句总是正确的:

if each == opList[2] or opList[3]:

if each == opList[0] or opList[1]:

你想要更像这样的东西:

if each == opList[2] or each == opList[3]:

等等。

可能还有其他问题,但肯定会让您的程序失效。