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

news2025/4/8 10:25:43

本系列为加州伯克利大学著名 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 / 阶乘

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

让编程变成一种享受-明基RD320U显示器

引言 作为一名有着多年JAVA开发经验的从业者&#xff0c;在工作过程中&#xff0c;显示器的重要性不言而喻。它不仅是我们与代码交互的窗口&#xff0c;更是影响工作效率和体验的关键因素。在多年的编程生涯中&#xff0c;我遇到过各种各样的问题。比如&#xff0c;在进行代码…

10分钟上手DeepSeek开发:SpringBoot + Vue2快速构建AI对话系统

作者&#xff1a;后端小肥肠 目录 1. 前言 为什么选择DeepSeek&#xff1f; 本文技术栈 2. 环境准备 2.1. 后端项目初始化 2.2. 前端项目初始化 3. 后端服务开发 3.1. 配置文件 3.2. 核心服务实现 4. 前端服务开发 4.1. 聊天组件ChatWindow.vue开发 5. 效果展示及源…

Linux环境开发工具

Linux软件包管理器yum Linux下安装软件方式&#xff1a; 源代码安装rpm安装——Linux安装包yum安装——解决安装源、安装版本、安装依赖的问题 yum对应于Windows系统下的应用商店 使用Linux系统的人&#xff1a;大部分是职业程序员 客户端怎么知道去哪里下载软件&#xff1…

JupyterNotebook高级使用:常用魔法命令

%%writefile test.py def Test(name):print("Test",name,"success")运行结果&#xff1a;就是在我们的文件目录下面创建了这个test.py文件&#xff0c;主要是认识一下这个里面的%%writefile表示创建新的文件&#xff0c;这个文件里面的内容就是上面我们定义…

C++ Primer 类的作用域

欢迎阅读我的 【CPrimer】专栏 专栏简介&#xff1a;本专栏主要面向C初学者&#xff0c;解释C的一些基本概念和基础语言特性&#xff0c;涉及C标准库的用法&#xff0c;面向对象特性&#xff0c;泛型特性高级用法。通过使用标准库中定义的抽象设施&#xff0c;使你更加适应高级…

50页PDF|数字化转型成熟度模型与评估(附下载)

一、前言 这份报告依据GBT 43439-2023标准&#xff0c;详细介绍了数字化转型的成熟度模型和评估方法。报告将成熟度分为五个等级&#xff0c;从一级的基础转型意识&#xff0c;到五级的基于数据的生态价值构建与创新&#xff0c;涵盖了组织、技术、数据、资源、数字化运营等多…

机器学习实战(8):降维技术——主成分分析(PCA)

第8集&#xff1a;降维技术——主成分分析&#xff08;PCA&#xff09; 在机器学习中&#xff0c;降维&#xff08;Dimensionality Reduction&#xff09; 是一种重要的数据处理技术&#xff0c;用于减少特征维度、去除噪声并提高模型效率。主成分分析&#xff08;Principal C…

前端插件使用xlsx-populate,花样配置excel内容,根据坐添加标替换excel内容,修改颜色,合并单元格...。

需求要求&#xff1a;业务人员有个非常复杂得excel表格&#xff0c;各种表头等&#xff0c;但是模板是固定得。当然也可以实现在excel上搞出各种表格&#xff0c;但是不如直接用已有模板替换其中要动态得内容方便&#xff0c;这里我们用到CSDN得 xlsx-populate 插件。 实列中我…

分布式大语言模型服务引擎vLLM论文解读

论文地址&#xff1a;Efficient Memory Management for Large Language Model Serving with PagedAttention 摘要 大语言模型&#xff08;LLMs&#xff09;的高吞吐量服务需要一次对足够多的请求进行批处理。然而&#xff0c;现有系统面临困境&#xff0c;因为每个请求的键值…

如何开发一个大模型应用?

1. 背景 AIGC技术的突破性进展彻底改变了技术开发的范式&#xff0c;尤其是以GPT为代表的LLM&#xff0c;凭借其强大的自然语言理解与生成能力&#xff0c;迅速成为全球科技领域的焦点。2023年末&#xff0c;随着ChatGPT的爆火&#xff0c;AIGC技术从实验室走向规模化应用&…

[数据结构]二叉搜索树详解

目录 一、二叉搜索树的概念 二、二叉搜索树的性能分析 三、二叉搜索树的中序遍历用于排序去重 四、二叉搜索树的查找 1、查找的非递归写法 2、查找的递归写法 五、二叉搜索树的插入 1、插入的非递归写法 2、插入的递归写法 六、二叉搜索树的删除 1、删除的非递归写法…

撕碎QT面具(2):groupBox内容居中显示

问题描述&#xff1a; 当笔者在GroupBox中使用Form Layout构建图中内容时&#xff0c;不能居中显示。 解决方案&#xff1a; 1、首先在form layout左右添加横向弹簧&#xff0c;并ctrl进行选中这三个控件。点击水平布局&#xff0c;让中间的控件不变形。 2、选中groupBox&#…

SpringBoot速成(14)文件上传P23-P26

1. 什么是 multipart/form-data&#xff1f; 想象一下&#xff0c;你有一个包裹要寄给朋友&#xff0c;但包裹里有不同类型的东西&#xff1a;比如一封信&#xff08;文字&#xff09;、一张照片&#xff08;图片&#xff09;和一个小礼物&#xff08;文件&#xff09;。为了确…

图论入门算法:拓扑排序(C++)

上文中我们了解了图的遍历(DFS/BFS), 本节我们来学习拓扑排序. 在图论中, 拓扑排序(Topological Sorting)是对一个有向无环图(Directed Acyclic Graph, DAG)的所有顶点进行排序的一种算法, 使得如果存在一条从顶点 u 到顶点 v 的有向边 (u, v) , 那么在排序后的序列中, u 一定…

【iOS】SwiftUI状态管理

State ObservedObject StateObject 的使用 import SwiftUIclass CountModel: ObservableObject {Published var count: Int 0 // 通过 Published 标记的变量会触发视图更新init() {print("TimerModel initialized at \(count)")} }struct ContentView: View {State…

自制简单的图片查看器(python)

图片格式&#xff1a;支持常见的图片格式&#xff08;JPG、PNG、BMP、GIF&#xff09;。 import os import tkinter as tk from tkinter import filedialog, messagebox from PIL import Image, ImageTkclass ImageViewer:def __init__(self, root):self.root rootself.root.…

ChatGPT行业热门应用提示词案例-AI绘画类

AI 绘画指令是一段用于指导 AI 绘画工具&#xff08;如 DALLE、Midjourney 等&#xff09;生成特定图像的文本描述。它通常包含场景、主体、风格、色彩、氛围等关键信息&#xff0c;帮助 AI 理解创作者的意图&#xff0c;从而生成符合要求的绘画作品。 ChatGPT 拥有海量的知识…

Visual Studio Code的下载安装与汉化

1.下载安装 Visual Studio Code的下载安装十分简单&#xff0c;在本电脑的应用商店直接下载安装----注意这是社区版-----一般社区版就足够用了---另外注意更改安装地址 2.下载插件 重启后就是中文版本了

分词器(Tokenizer) | 有了分词器,为什么还需要嵌入模型

文章目录 什么是tokenizer有了分词器&#xff0c;为什么还需要嵌入模型分词器为什么在transformers 里Hugging Face的Tokenizer大模型不同tokenizer训练效果对比分词器库选择当前顶尖大模型所采用的 Tokenizer 方法与词典大小 参考 什么是tokenizer Tokenizers huggingface官方…

scala中 隐式转换

一、 隐式转换&#xff1a; 编译器 偷偷地&#xff0c;自动地帮我们把一种数据类型转换为另一种类型 例如&#xff1a; int --> double object test {// 复习隐式转换// 隐式转换&#xff1a; 编译器 偷偷地&#xff0c;自动地帮我们把一种数据类型转换为另一…