为什么不能在堆栈中压入多个数字来计算前缀?

问题描述 投票:0回答:1

我正在编写程序,正在将函数转换为前缀并进行计算。

from pythonds.basic import Stack

def doMath(op, op1, op2):

    if op == "*":
        return int(op1) * int(op2)

    elif op == "/":
        return int(op1) / int(op2)

    elif op == "+":
        return int(op1) + int(op2)

    elif op == "-":
        return int(op1) + int(op2)

    def postfixEval(postfixExpr):

    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        print(tokenList)
        print("this is token: ", token)

        if token in "0123456789":
            operandStack.push(token)
            print("pop: ",operandStack.peek())

        elif not operandStack.isEmpty():
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            print (result)
            operandStack.push(result)

    return operandStack.pop()

print(postfixEval('7 8 + 3 2 + /'))
print(postfixEval("17 10 + 3 * 9 /"))

所以当我运行第一个postfixEval时,它返回3.0,但在第二次打印时返回IndexError: pop from empty list显然是2位数的BC,我该如何解决?

谢谢

python python-3.x stack push
1个回答
0
投票

if token in "0123456789"替换if token.isdigit():

© www.soinside.com 2019 - 2024. All rights reserved.