《数据结构与算法Python语言描述》学习笔记chap6(2)表达式树

《数据结构与算法Python语言描述》学习笔记chap6(2)表达式树
二叉树的简单应用:表达式树

20191201
数学表达式具有分层次的递归结构,一个运算符作用域相应运算对象,其运算对象又可以是任意复杂的表达式。
二元表达式:可以映射的二叉树
1)以基本运算对象(数和变量)作为叶结点中的数据。
2)以运算符作为分支节点的数据:
其两棵子树都是它的运算对象;
子树可以是基本运算对象,也可以是任意复杂的二元表达式
使用tuple作为实现基础–返回结果算是一个tuple

isinstance(a,tuple)
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in isinstance(x, (A, B, …)), may be given as the target to check against. This is equivalent to isinstance(x, A) or isinstance(x, B) or … etc.
返回对象是一个类的实例还是其子类的实例。
可以将isinstance(x,(A,B,…))中的元组作为要检查的目标。 这等效于isinstance(x,A)或isinstance(x,B)或…等。

区分基本表达式(直接处理)和复合表达式(递归处理)
判断是否否为基本表达式
def id_basic_exp(a):
return not isinstance(a,tuple)

判断是否数值的函数:

# 送一表达式构造函数
def make_sum(a,b):
    return '+', a, b


def make_prod(a,b):
    return ('*',a,b)


def make_diff(a,b):
    return ('-',a,b)

def make_div(a,b):
    return ('/',a,b)


# 判断是否否为基本表达式
def is_basic_exp(a):
    return not isinstance(a,tuple)


# 判断是否数值的函数
def is_number(x):
    return (isinstance(x,int) or isinstance(x,float) or isinstance(x,complex))


def eval_sum(a,b):
    if is_number(a) and is_number(b):
        return a+b
    if is_number(a) and a == 0:
        return b
    if is_number(b) and b == 0:
        return a
    return make_sum(a,b)


def eval_div(a,b):
    if is_number(a) and is_number(b):
        return a / b
    if is_number(a) and a == 0:
        return b
    if is_number(b) and b == 0:
        return a
    return make_sum(a,b)


def eval_prod(a,b):
    if is_number(a) and is_number(b):
        return a * b
    if is_number(a) and a == 0:
        return b
    if is_number(b) and b == 0:
        return a
    return make_prod(a,b)

def eval_diff(a,b):
    if is_number(a) and is_number(b):
        return a - b
    if is_number(a) and a == 0:
        return b
    if is_number(b) and b == 0:
        return a
    return make_diff(a,b)


# 表达式求值
def eval_exp(e):
    if is_basic_exp(e):
        return e
    op,a,b = e[0],eval_exp(e[1]),eval_exp(e[2])
    if op == '+':
        return eval_sum(a,b)
    elif op == "-":
        return eval_diff(a,b)
    elif op == "*":
        return eval_prod(a,b)
    elif op == "/":
        return eval_div(a,b)
    else:
        raise ValueError("Unknown operator",op)



el = make_prod(3,make_sum(2,5))
print(el)
print(eval_exp(el))


el1 = make_prod(3,make_sum(make_diff(9,5),5))
print(el1)
print(eval_exp(el1))

运行结果:
(’’, 3, (’+’, 2, 5))
21
(’
’, 3, (’+’, (’-’, 9, 5), 5))
27

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值