简体   繁体   English

使用堆栈python评估postfix

[英]Evaluating postfix using stack python

My task is to convert a fully parenthesized infix expression. 我的任务是转换带括号的中缀表达式。 Example

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

to postfix. 后缀。 Then evaluate the postfix. 然后评估后缀。 The expression is input from the user. 该表达式是从用户输入的。 I have to use a class called Stack already written for me. 我必须使用已经为我编写的名为Stack的类。 It must not be modified: 不得修改:

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"

The first problem I have is that when the user inputs for example 54, while using stack, 5 and 4 are two different elements. 我遇到的第一个问题是,当用户输入例如54时,在使用堆栈时,5和4是两个不同的元素。 How can I turn it into one? 如何将它变成一个?

Here is the code I have so far so evaluating the postfix: 这是我到目前为止评估后缀的代码:

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)

I know the problem is the second to last line but I'm not sure how to fix it 我知道问题是倒数第二行,但是我不确定如何解决

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?" “我遇到的第一个问题是,当用户输入例如54时,在使用堆栈时,5和4是两个不同的元素。如何将其变成一个?”

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. 这是在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

when you write: 当你写:

for n in Postfix

you're iterating over the characters in Postfix one at a time. 您一次遍历Postfix中的字符。 You might do better to convert Postfix to a list of strings with a helper function along these lines to pad the operators if they're not padded 您可能最好通过以下几行使用辅助函数将Postfix转换为字符串列表,以填充运算符(如果未填充)

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

so now you can change 所以现在你可以改变

for n in Postfix

to

for n in foo(Postfix).split()

and it should solve the problem of not handling numbers properly. 并且应该解决不能正确处理数字的问题。

split() splits a string into a list of nonwhitespace strings, eg "hello world" would become ["hello", "world"] split()将字符串拆分为非空白字符串列表,例如,“ hello world”将变为[“ hello”,“ world”]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM