伯克利 CS61A 课堂笔记 10 —— Trees

本系列为加州伯克利大学著名 Python 基础课程 CS61A 的课堂笔记整理,全英文内容,文末附词汇解释。

目录

01 Trees 树

Ⅰ Tree Abstraction

Ⅱ Implementing the Tree Abstraction

02 Tree Processing 建树过程

Ⅰ Fibonacci tree

Ⅱ Tree Processing uses recursion

Ⅲ Creating Trees

03 Example: Printing Trees

04 Example: Summing Paths

05 Example: Counting Paths

附:词汇解释


01 Trees 树

Ⅰ Tree Abstraction

Recursive description (wooden trees):

        A tree has a root label and a list of branches.

        Each branch is a tree.

        A tree with zero branches is called a leaf.

Relative description (family trees):

        Each location in a tree is called a node.

        Each node has a label that can be any value.

        One node can be the parent/child of another.

Ⅱ Implementing the Tree Abstraction

>>> tree(3, [tree(1), tree(2, [tree(1), tree(1)])])
[3, [1], [2, [1], [1]]]
#Trees

def tree(label, branches=[]):
    #Verifies the tree definition
    for branch in branches:
        assert is_tree(branch)
    return [label] + list(branches)

def label(tree):
    return tree[0]

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

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

def is_tree(tree):
    #Verifies the tree definition
    if type(tree) != list or len(tree) < 1:
        return false
    for branch in branches(tree):
        if not is_tree(branch):
            return false
    return true
>>> tree(1)
[1]
>>> is_leaf(tree(1))
true

>>> t = tree(1, [tree(5, [tree(7)]), tree(6)])
>>> t
[1, [5, [7]], [6]]
>>> label(t)
1
>>> branches(t)
[[5, [7]], [6]]
>>> branches(t)[0]
[5, [7]]
>>> is_tree(branches(t)[0])
true
>>> label(branches(t)[0])
5

02 Tree Processing 建树过程

Ⅰ Fibonacci tree
def fib_tree(n):
    if n <= 1:
        return tree(n)
    else:
        left, right = fib_tree(n-2), fib_tree(n-1)
        return tree(label(left)+label(right), [left, right])
>>> fib_tree(0)
[0]
>>> fib_tree(1)
[1]
>>> fib_tree(2)
[1, [0], [1]]
>>> fib_tree(4)
[3, [1, [0], [1]], [2, [1], [1, [0], [1]]]]
>>> label(fib_tree(4))
3
Ⅱ Tree Processing uses recursion

Processing a leaf is often the base of a tree processing function.

The recursive case typically makes a recursive call on each branch, then aggregates the results.

def count_leaves(t):
    """Count the leaves of a tree."""
    if is_leaf(t):
        return 1
    else:
        #寻找分支的叶子
        return sum([count_leaves(b) for b in branches(t)])
>>> count_leaves(fib_tree(4))
5

>>> count_leaves(fib_tree(10))
89

Implement leaves, which returns a list of the leaf of a tree.

Hint: If you sum a list of lists, you get a list containing the elements of those lists.

>>> sum([[1], [2, 3], [4]], [])
[1, 2, 3, 4]
>>> sum([[1]], [])
[1]
>>> sum([[[1]], [2]], [])
[[1], 2]
def leaves(tree):
    """Return a list containing the leaf labels of tree.
    
    >>> leaves(fib_tree(4))
    [0, 1, 1, 0, 1]
    """
    
    if is_leaf(tree):
        return [label(tree)]
    else:
        #寻找分支的叶子
        return sum([leaves(b) for b in branches(tree)], [])
Ⅲ Creating Trees

A function that creates a tree from another tree is typically also recursive.

def increment_leaves(t):
    """Return a tree like t but with leaf labels incremented."""
    if is_leaf(t):
        return tree(label(t) + 1)
    else:
        return tree(label(t), [increment_leaves(b) for b in branches(t)])

def increment(t):
    """Return a tree like t but with all labels incremented."""
    return tree(label(t) + 1, [increment_leaves(b) for b in branches(t)])

03 Example: Printing Trees

#原始版
def print_tree(t):
    print(label(t))
    for b in branches(t):
        print_tree(b)
>>> print_tree(fib_tree(4))
3
1
0
1
2
1
1
0
1
#升级版
def print_tree(t, indent=0){
    print(' ' * indent + str(label(t)))
    for b in branches(t):
    	print_tree(b, indent + 1)
}
>>> print_tree(fib_tree(4))
3
 1
  0
  1
 2
  1
  1
   0
   1

04 Example: Summing Paths

def fact(n):
    "Return n * (n-1) * ... * 1"
    if n == 0:
        return 1
    else:
        return n * fact(n - 1)

def fact_times(n, k):
    "Return k * n * (n-1) * ... * 1"
    if n == 0:
        return k
    else:
        return fact_times(n - 1, k * n)

def fact_plus(n):
    return fact_times(n, 1)
>>> fact_plus(4)
24
from tree import *

numbers = tree(3, [tree(4), tree(5, [tree(6)])])

haste = tree('h', [tree('a', [tree('s'),
                              tree('t')]),
                   tree('e')])

def print_sums(t, so_far):
    so_far = so_far + label(t)
    if is_leaf(t):
        print(so_far)
    else:
        for b in branches(t):
            print_sums(b, so_far)
>>> print_sums(numbers, 0)
7
14
>>> print_sums(haste, '')
has
hat
he

05 Example: Counting Paths

Count paths that have a total label sum.

def count_paths(t, total):
    """Return the number of paths from the root to any node in tree t
    for which the labels along the path sum to total.
    
    >>> t = tree(3, [tree(-1), tree(1, [tree(2, [tree(1)]), tree(3)]), tree(1, [tree(-1)])])
    >>> count_paths(t, 3)
    2
    >>> count_paths(t, 4)
    2
    >>> count_paths(t, 5)
    0
    >>> count_paths(t, 6)
    1
    >>> count_paths(t, 7)
    2
    """
    
    if label(t) == total:
        found = 1
    else:
        found = 0
    return found + sum(count_paths(b, total - label(t)) for b in branches(t))

附:词汇解释

verify 证明、definition 定义、aggregate / ˈæɡrɪɡət / 合计、hint / hɪnt / 提示、increment / ˈɪŋkrəmənt / 增长、indent / ɪnˈdent / 缩进、factorial / fækˈtɔːriəl / 阶乘

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/972887.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Spring Boot 定时任务:轻松实现任务自动化

在现代应用开发中&#xff0c;定时任务是一个常见的需求。比如&#xff0c;我们可能需要定时清理过期数据、定时发送邮件通知等。 操作流程 开启定时任务注解 在启动类添加注解EnableScheduling 设置时间&#xff08;固定时间间隔&#xff09; 使用 Scheduled 注解创建定时…

通过监督微调提升多语言大语言模型性能

引言 澳鹏助力一家全球科技公司提升其大语言模型&#xff08;LLM&#xff09;的性能。通过提供结构化的人工反馈形式的大语言模型训练数据&#xff0c;让该模型在30多种语言、70多种方言中的表现得到优化。众包人员们进行多轮对话&#xff0c;并依据回复的相关性、连贯性、准确…

Flask实现高效日志记录模块

目录 一. 简介&#xff1a; 1. 为什么需要请求日志 二. 日志模块组成 1. 对应日志表创建&#xff08;包含日志记录的关键字段&#xff09; 2. 编写日志记录静态方法 3. 在Flask中捕获请求日志 4. 捕获异常并记录错误日志 5. 编写日志接口数据展示 6. 写入数据展…

【学习笔记】Cadence电子设计全流程(一)Cadence 生态及相关概念

【学习笔记】Cadence电子设计全流程&#xff08;一&#xff09;Cadence 生态及相关概念 1.1 Cadence 生态系统及各模块关系1.2 Cadence相较于Altium Designer在硬件设计中的优势 1.1 Cadence 生态系统及各模块关系 Cadence 提供了一套完整的电子设计自动化 (EDA) 工具链&#…

【Linux Redis】关于用docker拉取Redis后,让虚拟机运行起来redis,并使得其可以连接到虚拟机外的navicat。

步骤一&#xff1a;拉取Redis镜像 docker pull redis 这个命令会下载最新版本的Redis镜像到你的本地Docker仓库中。你也可以指定一个具体的版本号&#xff0c;例如docker pull redis:6.2.6&#xff0c;来拉取特定版本的Redis镜像。 如果拉取遇到问题请参考【Linux AnolisOS】关…

蓝桥与力扣刷题(蓝桥 裁纸刀)

本题为填空题&#xff0c;只需要算出结果后&#xff0c;在代码中使用输出语句将所填结果输出即可。 题目&#xff1a;小蓝有一个裁纸刀&#xff0c;每次可以将一张纸沿一条直线裁成两半。 小蓝用一张纸打印出两行三列共 6 个二维码&#xff0c;至少使用九次裁出来&#xff0c…

pdf转换成word在线 简单好用 支持批量转换 效率高 100%还原

pdf转换成word在线 简单好用 支持批量转换 效率高 100%还原 在数字化办公的浪潮中&#xff0c;文档格式转换常常让人头疼不已&#xff0c;尤其是 PDF 转 Word 的需求极为常见。PDF 格式虽然方便阅读和传输&#xff0c;但难以编辑&#xff0c;而 Word 格式却能灵活地进行内容修…

Django ModelForm使用(初学)

1.目的是根据员工表字段&#xff0c;实现一个新增员工的数据填写页面 2.在views.py文件中按下面的格式写 定义 ModelForm 类&#xff1a;UserModelForm &#xff08;自己命名的类名&#xff09;使用时需要导入包 定义视图函数&#xff1a;user_model_form_add&#xff08;在函…

基于大牛直播SDK的Android平台低延迟RTSP|RTMP播放与录像技术实践

技术背景 随着直播、安防监控、远程会议等场景对实时性与稳定性要求的提升&#xff0c;低延迟流媒体播放与录像成为核心技术需求。大牛直播SDK的SmartPlayer模块提供了完整的解决方案&#xff0c;支持RTSP、RTMP协议的多实例播放、硬件解码、实时快照、录像管理等功能&#xf…

小怿学习日记(七) | Unreal引擎灯光架构

灯光的布局对于HMI场景中车模的展示效果有着举足轻重的地位。本篇内容将简单介绍ES3.1的相关知识&#xff0c;再深入了解Unreal引擎中车模的灯光以及灯光架构。 一、关于ES3.1 1.1 什么是ES3.1 ES3.1这个概念对于美术的同学可能比较陌生&#xff0c;ES3.1指的是OpenGL ES3.1&…

DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方DeepSeek接入)

前言 在当今数字化时代&#xff0c;AI编程助手已成为提升开发效率的利器。DeepSeek作为一款强大的AI模型&#xff0c;凭借其出色的性能和开源免费的优势&#xff0c;成为许多开发者的首选。今天&#xff0c;就让我们一起探索如何将DeepSeek接入PyCharm&#xff0c;实现高效、智…

广度优先搜索详解--BFS--蒟蒻的学习之路

1.什么是广度优先搜索? 广度优先搜索&#xff08;Breadth-First Search&#xff0c;简称BFS&#xff09;是一种遍历或搜索树和图的算法&#xff0c;也称为宽度优先搜索&#xff0c;BFS算法从图的某个节点开始&#xff0c;依次对其所有相邻节点进行探索和遍历&#xff0c;然后再…

. Unable to find a @SpringBootConfiguration(默认软件包中的 Spring Boot 应用程序)

解决&#xff1a; 新建一个包即可 问题&#xff1a; 默认软件包中的 Spring Boot 应用程序。 原因&#xff1a; 默认包的定义 &#xff1a; 如果一个 Java 类没有使用 package 声明包名&#xff0c;则该类会被放置在默认包中。Spring Boot 遵循 Java 的包管理约定&#xff…

DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地

对于个人开发者或尝鲜者而言&#xff0c;本地想要部署 DeepSeek 有很多种方案&#xff0c;但是一旦涉及到企业级部署&#xff0c;则步骤将会繁琐很多。 比如我们的第一步就需要先根据实际业务场景评估出我们到底需要部署什么规格的模型&#xff0c;以及我们所要部署的模型&…

“三次握手”与“四次挥手”:TCP传输控制协议连接过程

目录 什么是TCP协议 “三次握手”建立连接 “四次挥手”断开连接 “三次握手”和“四次挥手”的反思 总结 什么是TCP协议 想象一下&#xff0c;你和远方的朋友要进行一场电话交流&#xff0c;但这通电话不仅仅是随便聊聊&#xff0c;而是要传递一封重要的信件。为了确保这…

网络运维学习笔记 012网工初级(HCIA-Datacom与CCNA-EI)某机构新增:GRE隧道与EBGP实施

文章目录 GRE隧道&#xff08;通用路由封装&#xff0c;Generic Routing Encapsulation&#xff09;协议号47实验&#xff1a;思科&#xff1a;开始实施&#xff1a; 华为&#xff1a;开始实施&#xff1a; eBGP实施思科&#xff1a;华为&#xff1a; GRE隧道&#xff08;通用路…

Android 动态加入Activity 时 manifest 注册报错解决。使用manifestPlaceholders 占位

需求如下&#xff1a; 项目 测试demo 有多个渠道&#xff0c;部分渠道包含支付功能&#xff0c;在主测试代码外&#xff0c;需要一个单独 Activity 调用测试代码。 MainActivityPayActivity渠道A包含不包含渠道B包含包含 因为支付功能需要引入对应的 moudule&#xff0c;因此…

【koa】05-koa+mysql实现数据库集成:连接和增删改查

前言 前面我们已经介绍了第二阶段的第1-4点内容&#xff0c;本篇介绍第5点内容&#xff1a;数据库集成&#xff08;koamysql&#xff09; 也是第二阶段内容的完结。 一、学习目标 在koa项目中正常连接数据库&#xff0c;对数据表进行增删改查的操作。 二、操作步骤 本篇文章…

linux--关于makefile

makefile文件 可以指定编译顺序&#xff0c;这样方便一个项目的多个文件要编译的挨个操作的麻烦。 makefile文件的命名&#xff1a;makefile 或者 Makefile 必须是这俩&#xff0c;系统才能识别 规则的书写语法如下&#xff1a; 一个makefile内可以有多个规则 目标:依赖a 依…

俄罗斯方块游戏完整代码示例

以下是一个基于Cocos Creator引擎开发的俄罗斯方块游戏的完整代码示例。该游戏实现了俄罗斯方块的基本功能&#xff0c;并且代码整合在单个文件中&#xff0c;无需任何外部依赖&#xff0c;可以直接在浏览器中运行。 1. 创建Cocos Creator项目 首先&#xff0c;确保你已经安装了…