我正在写一个程序,我正在把一个函数转换成前缀和计算
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 /"))
因此,当我运行第一次修复后评估时,它返回3.0,
但在第二次打印时,它返回IndexError: pop from empty list
很明显,这是两位数的bc,我怎么能修正它呢
谢谢
当您尝试时:
对于
token = 17
,这将失败,因为17
不在0123456789
中。因此,将其更改为:
工作原理:
当传递包含数字和数字的
str
类型时,float()
尝试将其转换为浮点。只有当它是一个数字时,这才可能将
if token in "0123456789"
(检查token
是否是"0123456789"
的子字符串)替换为if token.isdigit()
(检查token
是否由十进制数字组成)相关问题 更多 >
编程相关推荐