我的任务是使用堆栈评估一个完全带括号的中缀表达式。 Stack类已经为我编写了,我不能修改或修改Stack类。评估中缀表达式python
下面是如何评价中缀表达式一步一步的方向:
只需扫描表达由左到右。如果它不是a),请将其推入堆栈。 当您遇到a)时,从堆栈中弹出4次,执行数学运算并将值推入堆栈。 最后你会在堆栈中有一个值,这将是答案。
这里是代码:
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
这里是我的代码运行的例子:我觉得这个问题
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'
你能提供一些输入的例子,你的代码与输入干什么,你想它与输入做些什么呢? – 2013-05-07 22:43:04
如果你打算使用eval,编写解析器有什么意义? – Eric 2013-05-07 22:58:47
如果你允许使用eval来表达它,那么要容易得多,如果你必须解析嵌套的parens,那么你需要学习经验。 – dansalmo 2013-05-07 23:19:00