评估中缀表达式python [英] Evaluating an infix expression python
问题描述
我的任务是使用堆栈计算完全括号中的中缀表达式.已经为我编写了一个 Stack 类,我不能更改或修改 Stack 类.
My task is to evaluate a fully parenthesized infix expression using a stack. A Stack class has been written for me and I must not change or modify the Stack class.
以下是如何计算中缀表达式的分步说明:
Here are the step by step directions for how to evaluate the infix expression:
只需从左到右扫描表达式.如果它不是 a ),则将其压入堆栈.当您遇到 a ) 时,从堆栈中弹出 4 次,进行数学运算并将值压入堆栈.最后,堆栈中将只有一个值,这就是答案.
Just scan the expression from left to right. If it is anything other than a ), push it onto the stack. When you encounter a ), pop from the stack 4 times, do the math and push the value onto the stack. At the end you will have just one value in the stack and that will be the answer.
代码如下:
class Stack:
def __init__(self):
self.theStack=[]
def top(self):
if self.isEmpty():
return "Empty Stack"
else:
return self.theStack[-1]
def isEmpty(self):
return len(self.theStack)==0
def push(self,item):
self.theStack.append(item)
def pop(self):
if not self.isEmpty():
temp=self.theStack[-1]
del(self.theStack[-1])
return temp
else:
return "Empty Stack"
这是我目前的代码:
def evaluateInfix(Input):
xStack=Stack()
for n in Input:
if n!=")":
print "Pushing %s into the stack" %n
xStack.push(n)
if n==")":
math=xStack.pop()+xStack.pop()+xStack.pop()
last=xStack.pop()
for j in math:
print " Popping %s from stack" %j
print " Popping %s from stack" %last
evaluation=eval(math)
xStack.push(evaluation)
print "Pushing %d into stack" %evaluation
这是我的代码运行示例:
Here is an example of my code running:
Enter a fully parenthesized expression that has non-negative integer operands and using only + - * and ( )
Please enter the expression: ((9+9)+(9+9))
Pushing ( into the stack
Pushing ( into the stack
Pushing 9 into the stack
Pushing + into the stack
Pushing 9 into the stack
Popping 9 from stack
Popping + from stack
Popping 9 from stack
Popping ( from stack
Pushing 18 into stack
Pushing + into the stack
Pushing ( into the stack
Pushing 9 into the stack
Pushing + into the stack
Pushing 9 into the stack
Popping 9 from stack
Popping + from stack
Popping 9 from stack
Popping ( from stack
Pushing 18 into stack
Traceback (most recent call last):
File "project2.py", line 252, in <module>
main()
File "project2.py", line 246, in main
Infix=evaluateInfix(Input)
File "project2.py", line 164, in evaluateInfix
math=xStack.pop()+xStack.pop()+xStack.pop()
TypeError: unsupported operand type(s) for +: 'int' and 'str'
推荐答案
希望对你有帮助
这篇关于评估中缀表达式python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!