《数据结构与算法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