栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python实现后序表达式计算(代码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python实现后序表达式计算(代码)

首先使用一个函数完成输入中序转后序
中序转后序前面的博客有写
Python使用栈将中序转后序(代码)

from pythonds.basic import Stack  # 引入栈


def infix_to_postfix(infix_expr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    op_stack = Stack()
    postfix_list = []

    # tokenList = infixexpr.split()
    token_list = list(infix_expr)
    numb = 0
    for token in token_list:
        if token in "0123456789":
            numb = numb * 10 + int(token)  # 这里针对多位数
        else:
            if numb != 0:
                postfix_list.append(numb)
                numb = 0
            if token == '(':

                op_stack.push(token)
            elif token == ')':
                top_token = op_stack.pop()
                while top_token != '(':
                    postfix_list.append(top_token)
                    top_token = op_stack.pop()
            else:
                while (not op_stack.isEmpty()) and (prec[op_stack.peek()] >= prec[token]):
                    postfix_list.append(op_stack.pop())
                op_stack.push(token)

    while not op_stack.isEmpty():
        postfix_list.append(op_stack.pop())
    return postfix_list
    # return " ".join(postfixList)


print(infix_to_postfix("(11+22)*(13+4)"))

然后使用后序进行计算

def postfix_evaluate(postfix_expr):  # 读进来要求是后序表达式
    operand_stack = Stack()  # 实例化栈(operand:操作数)

    for token in postfix_expr:
        if isinstance(token, int):
            # isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()
            operand_stack.push(int(token))  # 是数字就入栈
        else:
            operand2 = operand_stack.pop()
            operand1 = operand_stack.pop()
            # 取出堆栈上面的两个数
            result = do_math(token, operand1, operand2)
            # 调用函数进行运算
            operand_stack.push(result)  # 将结果入栈

    return operand_stack.pop()  # 返回最终运算结束后栈的内容,即返回计算结果


def do_math(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    else:
        return op1 - op2


print(postfix_evaluate(infix_to_postfix("(11+22)*(13+4)")))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/858693.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号