定义:
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])
结合了迭代的知识,个人觉的比较复杂。迭代涉及到数学归纳,从微观的计算验证和迭代理解容易混乱,从宏观和感觉上把握比较好。