先走一遍,

前面很多知道点,都串起来了。

# coding = utf-8

# 使用列表实现栈的功能
class Stack:
    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)

# 使用递归实现二叉树基本功能
class BinaryTree:
    def __init__(self, root_obj):
        self.key = root_obj
        self.left_child = None
        self.right_child = None

    def insert_left(self, new_node):
        node = BinaryTree(new_node)
        if self.left_child is None:
            self.left_child = node
        else:
            node.left_child = self.left_child
            self.left_child = node

    def insert_right(self, new_node):
        node = BinaryTree(new_node)
        if self.right_child is None:
            self.right_child = node
        else:
            node.right_child = self.right_child
            self.right_child = node

    def get_right_child(self):
        return self.right_child

    def get_left_child(self):
        return self.left_child

    def set_root_val(self, obj):
        self.key = obj

    def get_root_val(self):
        return self.key

# 建立一个算术分析树
def build_parse_tree(fp_exp):
    fp_list = fp_exp.split()
    p_stack = Stack()
    e_tree = BinaryTree('')
    p_stack.push(e_tree)
    current_tree = e_tree

    for item in fp_list:
        if item == '(':
            current_tree.insert_left('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_left_child()
        elif item not in ['+', '-', '*', '/', ')']:
            current_tree.set_root_val(int(item))
            parent = p_stack.pop()
            current_tree = parent
        elif item in ['+', '-', '*', '/']:
            current_tree.set_root_val(item)
            current_tree.insert_right('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_right_child()
        elif item == ')':
            current_tree = p_stack.pop()
        else:
            raise ValueError
    return e_tree

# 匹配加减乘除规则
class DoMatch:
    @staticmethod
    def add(op1, op2):
        return op1 + op2

    @staticmethod
    def sub(op1, op2):
        return op1 - op2

    @staticmethod
    def mul(op1, op2):
        return op1 * op2

    @staticmethod
    def true_div(op1, op2):
        return op1 / op2

# 算术分析式的求值
def evaluate(parse_tree):
    operator = DoMatch()
    opers = {'+': operator.add,
             '-': operator.sub,
             '*': operator.mul,
             '/': operator.true_div
             }
    left_c = parse_tree.get_left_child()
    right_c = parse_tree.get_right_child()

    if left_c and right_c:
        fn = opers[parse_tree.get_root_val()]
        return fn(evaluate(left_c), evaluate(right_c))
    else:
        return parse_tree.get_root_val()

# 前序遍历
def pre_order(tree):
    if tree:
        print(tree.get_root_val())
        pre_order(tree.get_left_child())
        pre_order(tree.get_right_child())

# 后序遍历
def post_order(tree):
    if tree:
        print(tree.get_root_val())
        post_order(tree.get_left_child())
        post_order(tree.get_right_child())

# 中序遍历
def in_order(tree):
    if tree:
        print(tree.get_root_val())
        in_order(tree.get_left_child())
        in_order(tree.get_right_child())

# 分析树打印
def print_exp(tree):
    s_val = ''
    if tree:
        s_val = '(' + str(print_exp(tree.get_left_child()))
        s_val = s_val + str(tree.get_root_val())
        s_val = s_val + str(print_exp(tree.get_right_child())) + ')'
    return s_val

pt = build_parse_tree("( ( 7 + 3 ) * ( 5 - 2 ) )")
print('=========pre_order================')
pre_order(pt)
print('=========post_order================')
post_order(pt)
print('=========in_order================')
in_order(pt)
print('=========print_exp================')
print(print_exp(pt))
print('=========evaluate================')
print(evaluate(pt))

  

=========pre_order================
*
+
7
3
-
5
2
=========post_order================
*
+
7
3
-
5
2
=========in_order================
*
+
7
3
-
5
2
=========print_exp================
(((7)+(3))*((5)-(2)))
=========evaluate================
30

  

python---数学表达式的分析树实现的更多相关文章

  1. 常用排序算法的python实现和性能分析

    常用排序算法的python实现和性能分析 一年一度的换工作高峰又到了,HR大概每天都塞几份简历过来,基本上一天安排两个面试的话,当天就只能加班干活了.趁着面试别人的机会,自己也把一些基础算法和一些面试 ...

  2. (转)Python数学函数

    原文:https://www.cnblogs.com/lpl1/p/7793645.html PYTHON-基础-内置函数小结----------http://www.wklken.me/posts/ ...

  3. 基于语法分析器GOLD Parser开发的数学表达式计算器

    最近发现一款文法分析神器,看完官网(http://goldparser.org/)的介绍后感觉很犀利的样子,于是就拿来测试了一番,写了一个数学表达式分析的小程序,支持的数学运算符如下所示:常规运算:+ ...

  4. 《构建之法》教学笔记——Python中的效能分析与几个问题

    <构建之法:现代软件工程>中第2章对效能分析进行了介绍,基于的工具是VSTS.由于我教授的学生中只有部分同学选修了C#,若采用书中例子讲解,学生可能理解起来比较困难.不过所有这些学生都学习 ...

  5. #8 Python数学方法

    前言 前几节了解了Python的不同数据类型,有小伙伴会问,不同的数据类型之间是否可以相互转换?肯定是可以的,本篇博文主要记录数字类型的转换,其他类型的相互转换会在下几节记录,Here we go! ...

  6. python金融与量化分析------Matplotlib(绘图和可视化)

    -----------------------------------------------------------Matplotlib:绘图和可视化------------------------ ...

  7. Python数学建模-01.新手必读

    Python 完全可以满足数学建模的需要. Python 是数学建模的最佳选择之一,而且在其它工作中也无所不能. 『Python 数学建模 @ Youcans』带你从数模小白成为国赛达人. 1. 数学 ...

  8. Python数学建模-02.数据导入

    数据导入是所有数模编程的第一步,比你想象的更重要. 先要学会一种未必最佳,但是通用.安全.简单.好学的方法. 『Python 数学建模 @ Youcans』带你从数模小白成为国赛达人. 1. 数据导入 ...

  9. 【数据结构与算法Python版学习笔记】树——二叉树的应用:解析树

    解析树(语法树) 将树用于表示语言中句子, 可以分析句子的各种语法成分, 对句子的各种成分进行处理 语法分析树 程序设计语言的编译 词法.语法检查 从语法树生成目标代码 自然语言处理 机器翻译 语义理 ...

随机推荐

  1. Contains Duplicate I & III

    Contains Duplicate I Given an array of integers, find if the array contains any duplicates. Your fun ...

  2. UVALive 8519 Arrangement for Contests 2017西安区域赛H 贪心+线段树优化

    题意 等价于给一个数列,每次对一个长度为$K$的连续区间减一 为最多操作多少次 题解: 看样例猜的贪心,10分钟敲了个线段树就交了... 从1开始,找$[i,i+K]$区间的最小值,然后区间减去最小值 ...

  3. iperf3 不支持双工模式

    iperf 2.05的时候,客户端可以使用参数"-d"来进行双工测试,先测试发送,client向server发送数据,等到测试时间结束后(默认为10s,可以通过-t选项来更改),然 ...

  4. CF 489C 暴力处理

    题意: 给你 数的长度 m, 数的每个数的和 Sum: 输出 这个数最小值 和最大值 #include<bits/stdc++.h> using namespace std; int ma ...

  5. python学习第42、43天 HTML\CSS

    前端是什么? 帮助不了解后端程序的客户轻松使用程序的工具,可以提升工作效率,提供各种各样的体验. 通用的前端大致会使用三种语言,用在三个不同的方面对前端进行架构和优化,这里也只介绍这三种 web前端常 ...

  6. css之relative

    一.relative对absolute的限制作用 1.限制left/top/right/bottom定位.absolute默认是在也没的左上角,当父类设定为relative,absolute就被限制在 ...

  7. 3、SourceTree通过PUTTY连接GitLab

    一.生成公钥和私钥 使用命令行生成(两种生成方式选择一种即可) 1.安装SourceTree打开SourceTree,点击“命令行模式”. 2.输入如下命令生成key“example@example. ...

  8. 在 Confluence 中启用 HTTP 响应压缩

    Confluence 能够支持 HTTP 的 GZip 传输编码.这个意味着 Confluence 将可以把数据压缩后传输给用户,这种配置能够针对不稳定的互联网状态下的传输速度缓慢和不稳定并且能够降低 ...

  9. Confluence 6 属性的一个活动

    为了启用属性,使用上面描述的方法.针对所有的用户,属性每一个访问的页面,将会在你的应用服务器中进行记录,直到你对 Confluence 进行重启.请注意每次用户访问一个链接,一个单一的属性将会被打印出 ...

  10. Confluence 6 为空白空间编辑默认主页

    希望编辑默认(空白)空间内容模板: 在屏幕的右上角单击 控制台按钮 ,然后选择 General Configuration 链接. 在左侧的面板中选择 全局模板和蓝图(Global Templates ...