我的任務是使用堆棧評估一個完全帶括號的中綴表達式。 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