python数据结构之中缀表达式转后缀表达式(栈的应用)

1.设计的算法流程

  首先将一个中缀表达式从左到右的扫描,设计括号和操作符的优先级。

  然后遍历切片后的中缀表达式。遇到操作数就添加到后缀表达式的列表中去,遇到操作符就压入栈要求必须是操作符优先级大的在上面,

  遇到左括号就标记,然后呢再就按照无括号的方法遍历,直到遇到右括号,然后再将操作符弹出直至左括号,然后再接着遍历,遍历到最后之后,将

  栈里面的操作符弹出即可,完成中缀转后缀的操作。具体实现如下

from Stack import *

def infixToPostfix(infixexpr):
    prec={}
    prec['*']=3
    prec['/']=3
    prec['+']=2
    prec['-']=2
    prec['(']=1
    opStack=Stack()
    postfixlist,tokenlist=[],[]
    for mark in range(len(infixexpr)):
        tokenlist.append(infixexpr[mark])
    print(tokenlist)
    for token in tokenlist:
        if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in '0123456789':
            postfixlist.append(token)
        elif token=='(':
            opStack.push(token)
        elif token==')':
            topToken=opStack.pop()
            while topToken!="(":
                postfixlist.append(topToken)
                topToken=opStack.pop()
        else:
            while (not opStack.isempity()) and (prec[opStack.get_stack()]>=prec[token]):
                postfixlist.append(opStack.pop())
            opStack.push(token)
    while not opStack.isempity():
        postfixlist.append(opStack.pop())
    return " ".join(postfixlist)


if __name__ == '__main__':
    n='A+B*C'
    print(infixToPostfix(n))

这里将栈的get_stack方法修改了一下,变成拿到栈顶的数据。

猜你喜欢

转载自www.cnblogs.com/ares-python/p/12825658.html