2013-05-07 84 views
0

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

你能提供一些輸入的例子,你的代碼與輸入幹什麼,你想它與輸入做些什麼呢? – 2013-05-07 22:43:04

+2

如果你打算使用eval,編寫解析器有什麼意義? – Eric 2013-05-07 22:58:47

+0

如果你允許使用eval來表達它,那麼要容易得多,如果你必須解析嵌套的parens,那麼你需要學習經驗。 – dansalmo 2013-05-07 23:19:00

回答

0

是你沒有決定你想要放在你的堆棧上。有數字或字符串嗎?我不認爲這是最好的解決方案(你很明顯正在做一些班級任務,我不想給你解決方案),但是如果你決定只輸入字符串,那麼你只需要替換:

xStack.push(evaluation) 

通過

xStack.push(str(evaluation)) 

但前面已經說過的評論,你可能不應該使用eval,並把整數和運營商在堆棧中。

0

的問題是,在你的代碼,這兩套「9 + 9」的作爲在EVAL字符串進行評估,然後放回堆棧整數。 (見下文)

theStack=['(', 18, '+', 18] 

因此,在代碼行:

math=xStack.pop()+xStack.pop()+xStack.pop() 

它試圖連接兩個整數(18和18)和一個串( '+'),創建一個錯誤這些是不兼容的類型。 如果你改變了這一行:

math=str(xStack.pop())+str(xStack.pop())+str(xStack.pop()) 

因此迫使一切是一個類型,字符串,它應該工作的罰款。