树(Tree)数据抽象

定义:
A tree has a root label and a sequence of branches. Each branch of a tree is a tree. A tree with no branches is called a leaf. Any tree contained within a tree is called a sub-tree of that tree (such as a branch of a branch). The root of each sub-tree of a tree is called a node in that tree. 重点:每一个branch都是tree,后面会给出例子

def tree (root_label, branches=[]):
	for branch in branches:
		assert is_tree(branch), 'branches must be trees'
	return [root_lable]+list(branches)

def lable(tree):
	return tree[0]

def branches(tree):
	return tree[1:]

def is_tree(tree):
	if type(tree)!=list or len(tree)<1:
		return False
	for branch in branches(tree):
		return False
	return True

给两个tree:
t1 = tree(1,[2]) t2 = tree(1,[tree(2)])
根据上面的函数,tree的branch应该是list并且也是tree, t1和t2看似都符合条件,实则t1不是tree。如果不检查branch是不是tree,t1和t2分别可得到:
t1 = [ 1,[2] ] t2 = [ 1,[[2]] ]
也就是说,[2]不是tree而[[2]]是。 这里有一个小知识点,对于 for x in list1 这个表达式,x会从list1的第一个值代入,直到检查到没有值了就跳过suite。因此,若list1=[ ] 为空,则直接跳过,点此验证
这里branch函数返回tree[1:]是slicing,自带一层 [ ], 保证了tree的迭代结构,t1, t2的验证图
上面代码可能比较长不能直接用链接,可复制代码

def branches(tree):
    return tree[1:]

def is_tree(tree):
    if type(tree)!=list or len(tree)<1:
        return False
    for branch in branches(tree):
        if not is_tree(branch):
            return False
    return True
    
def tree(root_label, branches=[]):
        for branch in branches:
            assert is_tree(branch), 'branches must be trees'
        return [root_label] + list(branches)
    

t2=tree(1,[tree(2)])
is_tree(t2)
t1=tree(1,[2])

结合了迭代的知识,个人觉的比较复杂。迭代涉及到数学归纳,从微观的计算验证和迭代理解容易混乱,从宏观和感觉上把握比较好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值