【问题标题】:Evaluating postfix using stack python使用堆栈python评估后缀
【发布时间】:2013-05-02 01:30:24
【问题描述】:

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

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

到后缀。然后评估后缀。表达式是用户输入的。 我必须使用已经为我编写的名为 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)

我知道问题是倒数第二行,但我不知道如何解决它

【问题讨论】:

    标签: python stack eval postfix-notation


    【解决方案1】:

    你问了几个问题(你的答案并不完整,就引导你达到评估后缀表达式的最终目标而言),但让我来解决你问的问题:

    “我遇到的第一个问题是,当用户输入例如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
    

    【讨论】:

      【解决方案2】:

      当你写作时:

      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() 将字符串拆分为非空白字符串列表,例如"hello world" 会变成 ["hello", "world"]

      【讨论】:

        猜你喜欢
        • 2012-05-01
        • 2011-08-03
        • 1970-01-01
        • 2015-05-03
        • 1970-01-01
        • 2014-07-01
        • 2011-12-14
        • 2013-10-11
        • 2015-02-14
        相关资源
        最近更新 更多