利用stack结构,将中缀表达式转换为后缀表达式并求值的算法实现

简介: #!/usr/bin/env python # -*- coding: utf-8 -*- # learn # Release 3.0 # chengang882 @ 2016-12-20 # 它可以将常见的中缀表达式转换成后缀表达式,并计算这个表达示的值 # Complete...
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# learn <<Problem Solving with Algorithms and Data Structures>>
# Release 3.0
# chengang882 @ 2016-12-20
# 它可以将常见的中缀表达式转换成后缀表达式,并计算这个表达示的值
# Completed implementation of a stack ADT


#数据结构
class Stack(object):
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

# 实现中缀表达式转换为后缀表达式
def infix_to_postfix(infix_expr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    op_stack = Stack()
    postfix_list = []
    # 一定要有空格切割,显得不完美
    token_list = infix_expr.split()

    for token in token_list:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfix_list.append(token)
        elif 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.is_empty()) and \
                  (prec[op_stack.peek()] >= prec[token]):
                postfix_list.append(op_stack.pop())
            op_stack.push(token)
    while not op_stack.is_empty():
        postfix_list.append(op_stack.pop())
    print(" ".join(postfix_list))
    return " ".join(postfix_list)


# 计算后缀表达式的值
def postfix_eval(postfix_expr):
    operand_stack = Stack()
    token_list = postfix_expr.split()

    for token in token_list:
        if token in "0123456789":
            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
    elif op == "-":
        return op1 - op2
    else:
        raise("ERROR")
    
if __name__ == "__main__":
    print(postfix_eval(infix_to_postfix("5 * 8 + 2 * 3")))
    infix_to_postfix("( A + B ) * C - ( D - E ) * ( F + G )")
    print(postfix_eval('7 8 + 3 2 + /'))

 输出:

>>> 
5 8 * 2 3 * +
46
A B + C * D E - F G + * -
3
>>> 

  

目录
相关文章
C4.
|
2月前
|
算法 程序员 C语言
C语言的选择结构与数据算法
C语言的选择结构与数据算法
C4.
19 0
|
1月前
|
负载均衡 算法 应用服务中间件
面试题:Nginx有哪些负载均衡算法?Nginx位于七层网络结构中的哪一层?
字节跳动面试题:Nginx有哪些负载均衡算法?Nginx位于七层网络结构中的哪一层?
42 0
|
5月前
|
算法 Java 程序员
【算法训练-队列 一】【结构特性】用两个栈实现队列
【算法训练-队列 一】【结构特性】用两个栈实现队列
30 0
|
7月前
|
算法 Java C++
【洛谷算法题】P5709-Apples Prologue / 苹果和虫子【入门2分支结构】
【洛谷算法题】P5709-Apples Prologue / 苹果和虫子【入门2分支结构】
|
7月前
|
算法
【洛谷算法题】P1425-小鱼的游泳时间【入门1顺序结构】
【洛谷算法题】P1425-小鱼的游泳时间【入门1顺序结构】
|
7月前
|
算法 C++
【洛谷算法题】P5707-上学迟到【入门1顺序结构】
【洛谷算法题】P5707-上学迟到【入门1顺序结构】
|
14天前
|
网络协议 算法 数据库
【专栏】OSPF是广泛应用的链路状态路由协议,通过分层网络结构和SPF算法实现高效路由。强烈建议收藏!
【4月更文挑战第28天】OSPF是广泛应用的链路状态路由协议,通过分层网络结构和SPF算法实现高效路由。其关键特性包括区域划分、链路状态数据库、邻居关系和路由更新。工作过程涉及邻居发现、信息交换、数据库构建、路由计算及收敛。理解OSPF对于网络管理和规划具有重要意义。
|
1月前
|
存储 算法
【算法与数据结构】深入解析二叉树(二)之堆结构实现
【算法与数据结构】深入解析二叉树(二)之堆结构实现
|
5月前
|
算法 安全 Java
【算法训练-栈 一】【结构特性】有效的括号、最小栈(包含Min函数的栈)
【算法训练-栈 一】【结构特性】有效的括号、最小栈(包含Min函数的栈)
36 0
|
2月前
|
算法
算法的三种基本结构
算法的三种基本结构
23 0