python 中后缀算法的中缀

Infix to postfix algorithm in python

对于我的数据结构 class 我必须使用 Python 创建一个基本的图形计算器 3. 要求是我们必须使用一个基本的 Stack class。用户以 "infix" 形式输入方程式,然后我应该将其转换为 "postfix" 以进行评估和绘图。我在使用中缀到后缀算法时遇到问题。我见过其他可行的算法,但我的教授希望它以某种方式完成。这是我目前所拥有的:

def inFixToPostFix():
inFix = '3*(x+1)-2/2'
postFix = ''
s = Stack()
for c in inFix:
    # if elif chain for anything that c can be
    if c in "0123456789x":
        postFix += c
    elif c in "+-":
        if s.isEmpty():
            s.push(c)
        elif s.top() =='(':
            s.push(c)
    elif c in "*/":
        if s.isEmpty():
            s.push(c)
        elif s.top() in "+-(":
            s.push(c)
    elif c == "(":
        s.push(c)
    elif c == ")":
        while s.top() is not '(':
            postFix += s.pop()
        s.pop()
    else:
        print("Error")
print(postFix)
return postFix

当我打印这个时,当预期结果为“3x1+*22/-”时,我得到“3x1+22” 任何帮助,将不胜感激。谢谢

您应该在退出循环后将剩余的操作数弹出堆栈。该算法非常简单,但如果您需要信息,请在此处进行解释:

http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html

如果您需要,这是我的解决方案版本:)

def toPostfix(infix):
    stack = []
    postfix = ''

    for c in infix:
        if isOperand(c):
            postfix += c
        else:
            if isLeftParenthesis(c):
                stack.append(c)
            elif isRightParenthesis(c):
                operator = stack.pop()
                while not isLeftParenthesis(operator):
                    postfix += operator
                    operator = stack.pop()              
            else:
                while (not isEmpty(stack)) and hasLessOrEqualPriority(c,peek(stack)):
                    postfix += stack.pop()
                stack.append(c)

    while (not isEmpty(stack)):
        postfix += stack.pop()
    return postfix

算法中需要大量修改才能使其正确。

  1. 将这种类型的字符串表示形式用于后缀字符串,稍后在评估它们时,您可能会得到 - 2+34 和 23+4 的相同表示是 234+
  2. 如果遇到的操作数的优先级低于操作数栈顶的操作数,则从操作数栈中弹出并压入后缀栈(你没有这样做)
  3. 操作数栈中剩余的操作数,在给定的中缀字符串遍历完成后,应该从中弹出并压入后缀栈。

这是数据结构课程的初始任务之一,因为它确实承认你使用 stacks.Thus 我不会分享我的代码,因为我认为你可以到达那里 yourself.Still困难,分享障碍,我会指引你通往目的地的道路。

class stack:
def __init__(self):
    self.item = []

def push(self,it):
    self.item.append(it)
def peek(self):
    if self.isempty() == True:
        return 0
    return self.item[-1]

def pop(self):
    if self.isempty() == True:
        return 0
    return(self.item.pop())

def length(self):
    return (len(self.item))


def isempty(self):
    if self.item == []:
        return True
    else:
        return False

def display(self):
    if self.isempty()== True:
        return
    temps = stack()
    while(self.isempty() != True):
        x = self.peek()
        print("~",x)
        temps.push(x)
        self.pop()
    while(temps.isempty() != True):
        x = temps.peek()
        self.push(x)
        temps.pop()


def isOperand(self, ch): 
    return ch.isalpha()
def notGreater(self, i):
    precedence = {'+':1, '-':1, '*':2, '/':2, '%':2, '^':3}
    if self.peek() == '(':
        return False
    a = precedence[i]
    b = precedence[self.peek()] 
    if a  <= b:
        return True
    else:
        return False
        


def infixToPostfix(self, exp):
    output = ""
    
    for i in exp:
        
        if self.isOperand(i) == True: # check if operand add to output
            print(i,"~ Operand push to stack")
            output = output + i

        # If the character is an '(', push it to stack 
        elif i  == '(':
            self.push(i)
            print(i," ~ Found ( push into stack")

        elif i == ')':  # if ')' pop till '('
            while( self.isempty() != True and self.peek() != '('):
                n = self.pop() 
                output = output + n
                print(n, "~ Operator popped from stack")
            if (self.isempty() != True and self.peek() != '('):
                print("_________")
                return -1
            else:
                x = self.pop()
                print(x, "Popping and deleting (")
        else: 
            while(self.isempty() != True and self.notGreater(i)):
                c = self.pop()
                output = output + c
                print(c,"Operator popped after checking precedence from stack")
            self.push(i)
            print(i,"Operator pushed to stack")

    # pop all the operator from the stack 
    while self.isempty() != True:
        xx = self.pop()
        output = output + xx
        print(xx,"~ pop at last")
    print(output)
    self.display()
st = stack()
st.infixToPostfix("a+(b*c)")

这是一个完整的算法,其中包含逐步的工作细节。

输出:

a ~ Operand push to stack
+ Operator pushed to stack
(  ~ Found ( push into stack
b ~ Operand push to stack
* Operator pushed to stack
c ~ Operand push to stack
* ~ Operator popped from stack
( Popping and deleting (
+ ~ pop at last
abc*+