0

私の仕事は、スタックを使用して完全に括弧で囲まれた中置式を評価することです。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'
4

3 に答える 3

0

これがあなたに役立つことを願っています

要旨を見る

于 2013-08-25T11:48:33.410 に答える
0

問題は、スタックに何を置きたくないかを決めていないことだと思います。数値または文字列はありますか? 私はそれが最善の解決策だとは思いません (あなたは明らかにクラスの割り当てを行っており、私はあなたに解決策を提供したくありません)、文字列のみを配置することにした場合は、次のように置き換えるだけです:

xStack.push(evaluation)

xStack.push(str(evaluation))

しかし、解説で既に述べたように、おそらく eval を使用せず、整数と演算子をスタックに置くべきです。

于 2013-07-14T20:43:59.190 に答える