评估中缀表达式python

时间:2013-05-07 22:35:17

标签: python stack infix-notation

我的任务是使用堆栈评估完全带括号的中缀表达式。已经为我编写了一个Stack类,我不能更改或修改Stack类。

以下是有关如何评估中缀表达式的分步说明:

只需从左到右扫描表达式。如果它不是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'

3 个答案:

答案 0 :(得分:0)

我认为问题在于你没有决定你要把什么放在你的筹码上。有数字还是字符串?我不认为这是最好的解决方案(你显然正在做一些课程作业而且我不想给你解决方案),但是如果你决定只放置字符串,你只需要替换:

xStack.push(evaluation)

通过

xStack.push(str(evaluation))

但正如评论中已经说过的,你可能不应该使用eval并将整数和运算符放在堆栈上。

答案 1 :(得分: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())

因此强制一切都是一种类型,字符串,它应该工作正常。

答案 2 :(得分:0)

我希望这会对你有所帮助

see the gist