0

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

(((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)

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

4

2 回答 2

0

There are a few questions you're asking (and your answer isn't complete, as far as leading you to your ultimate goal of evaluating a postfix expression), but let me address the one you ask:

"The first problem I have is that when the user inputs for example 54, while using stack, 5 and 4 are two different elements. How can I turn it into one?"

If you are committed to scanning the input one character at a time, then the simplest approach is to use a temporary variable. Here's a quick and dirty way to do it in 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
于 2013-05-07T23:52:53.933 回答
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() 将字符串拆分为非空白字符串列表,例如“hello world”将变为 ["hello", "world"]

于 2013-05-08T00:15:20.853 回答