我想编写一个Python代码,它将使用堆栈计算表达式。我有以下代码,其中numStk
是一个包含数字的堆栈,optStk
包含运算符。在表达式2+3*4-6
中,在for
循环的末尾,numStack
包含{12
,和{setOps()
函数从两个堆栈中弹出元素来计算表达式?在
def main():
raw_expression = input("Enter an expression: ")
expression = raw_expression.replace(" ", "")
for i in expression:
if (i in numbers):
numStk.push(i)
else:
setOps(i)
optStk.push(i)
## code needed to evaluate the rest of the elements in stackstack
return valStk.top()
我的setOps(i)
函数如下:
即使我填写了您遗漏的所有内容,您的代码也有问题:};您的计算顺序错误,例如,“6-5”被计算为“5-6”;您调用的是
setOps()
似乎被称为repeatOps()
;numStk
有时被称为{eval()
!在以下是我为解决上述问题而填写和修改您的代码:
远不是十全十美,但有些东西能让你前进:
示例
^{pr2}$为了解决您最初的问题,完成评估的关键似乎是使用一个虚构的低优先级运算符运行
setOps()
,如果optStk
中还剩下什么。在相关问题 更多 >
编程相关推荐