私の仕事は、スタックを使用して完全に括弧で囲まれた中置式を評価することです。Stack クラスは私のために書かれており、Stack クラスを変更したり変更したりしてはいけません。
中置式を評価する方法の段階的な指示は次のとおりです。
式を左から右にスキャンするだけです。) 以外の場合は、スタックにプッシュします。) に遭遇したら、スタックから 4 回ポップし、計算を行い、値をスタックにプッシュします。最後に、スタックに値が 1 つだけあり、それが答えになります。
そのコードは次のとおりです。
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'