为什么我不能在堆栈中推送多位数字来计算前缀?



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

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显然是两位数的bc,我该怎么修呢?

感谢

当您尝试时:

if token in "0123456789":
operandStack.push(token)

对于token = 17,这将失败,因为17不在0123456789
所以改为:

try:
if float(token):
operandStack.push(token)
except:
#your code here

这是如何工作的:
当传递包含数字和数字的str类型时,float()会尝试将其转换为浮点值。只有当它是一个数字时,这才有可能。

if token in "0123456789"(检查token是否是"0123456789"的子字符串(替换为if token.isdigit()(检查token是否由十进制数字组成(。

最新更新