CS61A Spring - Tree

版权声明:欢迎交流学习,转载请注明出处。 https://blog.csdn.net/qq_23869697/article/details/80534475

在学习sequence这一节中遇到比较困难的是Tree和link list。这里针对Tree做一些总结。

闭包closure property

In general, a method for combining data values has a closure property if the result of combination can itself be combined using the same method.
闭包的概念还是晦涩难懂。
我Google一下,这篇文章写得很好(一步一步教你认识Python闭包),可以耐心看看。
在了解闭包之前,我们需要知道作用域,全局变量和局部变量的概念,就像那篇文章的博主说的,闭包就是解决一个问题:脱离函数本身的作用域,局部变量还可以被访问。
一个简单的例子:
example
变量msg的作用范围是在调用print_msg函数,但是这个函数返回的是一个嵌套在print_msg函数中的一个嵌套函数printer(). 这个another就是一个闭包。调用他的时候,他能访问变量msg。

list and nesting lists

visualize lists in environment diagrams using box-and-pointer notation.
list

Tree

The tree is a fundamental data abstraction that imposes regularity on how hierarchical values are structured and manipulated.
树有根,节点,叶,分支等概念。
tree0

tree constructor and label selector, branches selector

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

The is_tree function is applied in the tree constructor to verify that all branches are well-formed.

>>> 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

The is_leaf function checks whether or not a tree has branches.

>>> def is_leaf(tree):
        return not branches(tree)

example:

def tree(root_label, branches=[]):
        for branch in branches:
            assert is_tree(branch), 'branches must be trees'
        return [root_label] + list(branches)
def label(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):
            if not is_tree(branch):
                return False
        return True

def is_leaf(tree):
        return not branches(tree)

t = tree(3, [tree(1), tree(2, [tree(1), tree(1)])])
label(t)
branches(t)
label(branches(t)[1])
is_leaf(t)
is_leaf(branches(t)[0])

一步一步教你认识Python闭包 https://foofish.net/python-closure.html
http://composingprograms.com/pages/23-sequences.html#trees
视频地址:
tree: https://www.youtube.com/watch?v=qFCJANh5ht8&list=PL6BsET-8jgYU_D4zfjxpO_ItfvMimn4Yv&index=6
tree processing: https://www.youtube.com/watch?v=gI2-CKJMgjE&index=7&list=PL6BsET-8jgYU_D4zfjxpO_ItfvMimn4Yv

猜你喜欢

转载自blog.csdn.net/qq_23869697/article/details/80534475
今日推荐