使用堆栈python评估postfix

时间:2013-05-07 23:19:05

标签: python stack eval postfix-notation

我的任务是转换完全带括号的中缀表达式。示例

  

(((54 + 56)+(4 + 73))+(9 + 7))

到postfix。然后评估后缀。表达式是来自用户的输入。 我必须使用一个已经为我编写的Stack类。不得修改:

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"

我遇到的第一个问题是,当用户输入例如54时,使用堆栈时,5和4是两个不同的元素。我怎么把它变成一个?

以下是我到目前为止评估后缀的代码:

OPERATOR=["+","-","*", "/"]

def evaluatePostfix(Postfix):
    eStack=Stack()
    for n in Postfix:
        if n not in OPERATOR and n!="(" and n!=")":
            eStack.push(n)
        if n in OPERATOR:
            math=eStack.pop()+n+eStack.pop()
            eval(math)

我知道问题是倒数第二行,但我不确定如何修复它

2 个答案:

答案 0 :(得分:0)

您提出了几个问题(并且您的答案并不完整,只要引导您达到评估后缀表达式的最终目标),但让我解决您提出的问题:

“我遇到的第一个问题是,当用户输入例如54时,使用堆栈时,5和4是两个不同的元素。如何将其转换为一个?”

如果您致力于一次扫描输入的一个字符,那么最简单的方法是使用临时变量。这是用Python快速而肮脏的方式。

infix = "54 + 490"
postfix = ""
a_number = None
OPERATOR = ["+", "-", "*", "/"]

for n in infix:
    if n not in OPERATOR and n != "(" and n != ")":
        if a_number is None:
            a_number = n
        else:
            a_number = a_number + n

    if n is ")" or n in OPERATOR:
         if a_number is not None:
             postfix += a_number
             a_number = None


if a_number is not None:
    postfix += a_number
    a_number = None

print postfix

答案 1 :(得分:0)

当你写:

for n in Postfix

你一次迭代一个Postfix中的字符。您可能最好将Postfix转换为带有帮助函数的字符串列表,如果它们没有填充则填充运算符

def foo(str):
 newstr = ""
 for x in str:
  if x not in "0123456789. ":
   newstr += " " + x + " "
  else:
   newstr += x
 return newstr

所以现在你可以改变

for n in Postfix

for n in foo(Postfix).split()

它应该解决不能正确处理数字的问题。

split()将字符串拆分为非空白字符串列表,例如“你好世界”将成为[“你好”,“世界”]