首页 > 编程语言 >Trees in python

Trees in python

时间:2025-01-01 09:52:02浏览次数:1  
标签:paths python Tree value label Trees path t1

The Tree class is defined as below.

class Tree:
    """
    >>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])
    >>> t.label
    3
    >>> t.branches[0].label
    2
    >>> t.branches[1].is_leaf()
    True
    """

    def __init__(self, label, branches=[]):
        for b in branches:
            assert isinstance(b, Tree)
        self.label = label
        self.branches = list(branches)

    def is_leaf(self):
        return not self.branches

    def __repr__(self):
        if self.branches:
            branch_str = ', ' + repr(self.branches)
        else:
            branch_str = ''
        return 'Tree({0}{1})'.format(self.label, branch_str)

    def __str__(self):
        def print_tree(t, indent=0):
            tree_str = '  ' * indent + str(t.label) + "\n"
            for b in t.branches:
                tree_str += print_tree(b, indent + 1)
            return tree_str

        return print_tree(self).rstrip()

Problem 3.2: Generate Paths (100 pts)

Define a generator function generate_paths which takes in a Tree t, a value value, and returns a generator object which yields each path from the root of t to a node that has label value.

t is implemented with a class, not as the function-based ADT.

Each path should be represented as a list of the labels along that path in the tree. You may yield the paths in any order.

def generate_paths(t, value):
    """Yields all possible paths from the root of t to a node with the label value
    as a list.

    >>> t1 = Tree(1, [Tree(2, [Tree(3), Tree(4, [Tree(6)]), Tree(5)]), Tree(5)])
    >>> print(t1)
    1
      2
        3
        4
          6
        5
      5
    >>> next(generate_paths(t1, 6))
    [1, 2, 4, 6]
    >>> path_to_5 = generate_paths(t1, 5)
    >>> sorted(list(path_to_5))
    [[1, 2, 5], [1, 5]]

    >>> t2 = Tree(0, [Tree(2, [t1])])
    >>> print(t2)
    0
      2
        1
          2
            3
            4
              6
            5
          5
    >>> path_to_2 = generate_paths(t2, 2)
    >>> sorted(list(path_to_2))
    [[0, 2], [0, 2, 1, 2]]
    """
    "*** YOUR CODE HERE ***"
solution dfs
def generate_paths(t, value):
    """Yields all possible paths from the root of t to a node with the label value
    as a list.
    >>> t1 = Tree(1, [Tree(2, [Tree(3), Tree(4, [Tree(6)]), Tree(5)]), Tree(5)])
    >>> print(t1)
    1
      2
        3
        4
          6
        5
      5
    >>> next(generate_paths(t1, 6))
    [1, 2, 4, 6]
    >>> path_to_5 = generate_paths(t1, 5)
    >>> sorted(list(path_to_5))
    [[1, 2, 5], [1, 5]]

    >>> t2 = Tree(0, [Tree(2, [t1])])
    >>> print(t2)
    0
      2
        1
          2
            3
            4
              6
            5
          5
    >>> path_to_2 = generate_paths(t2, 2)
    >>> sorted(list(path_to_2))
    [[0, 2], [0, 2, 1, 2]]
    """
    "*** YOUR CODE HERE ***"
    def helper(t,value,prev):
        #prev+=[t.label]
        if t.label==value:
            yield prev+[t.label]
        for b in t.branches:
            yield from helper(b,value,prev+[t.label])
    yield from helper(t,value,[])
a wrong solution
def generate_paths(t, value):
    """Yields all possible paths from the root of t to a node with the label value
    as a list.
    >>> t1 = Tree(1, [Tree(2, [Tree(3), Tree(4, [Tree(6)]), Tree(5)]), Tree(5)])
    >>> print(t1)
    1
      2
        3
        4
          6
        5
      5
    >>> next(generate_paths(t1, 6))
    [1, 2, 4, 6]
    >>> path_to_5 = generate_paths(t1, 5)
    >>> sorted(list(path_to_5))
    [[1, 2, 5], [1, 5]]

    >>> t2 = Tree(0, [Tree(2, [t1])])
    >>> print(t2)
    0
      2
        1
          2
            3
            4
              6
            5
          5
    >>> path_to_2 = generate_paths(t2, 2)
    >>> sorted(list(path_to_2))
    [[0, 2], [0, 2, 1, 2]]
    """
    "*** YOUR CODE HERE ***"
    def helper(t,value,prev):
        prev+=[t.label]
        if t.label==value:
            yield prev
        for b in t.branches:
            yield from helper(b,value,prev)
    yield from helper(t,value,[])
'''
错误原因:
在搜索完之后没有把变量prev还原成原来的模样,
在python中,list的赋值、传参都只是创造了一个引用关系,并不是一个copy,
因此在搜索branch1 的时候修改了prev的值会在 搜索branch2 的时候表现出来
'''

标签:paths,python,Tree,value,label,Trees,path,t1
From: https://www.cnblogs.com/yama-lei/p/18645323

相关文章

  • 计算机毕业设计Python+Spark考研预测系统 考研推荐系统 考研数据分析 考研大数据 大数
    温馨提示:文末有CSDN平台官方提供的学长联系方式的名片!温馨提示:文末有CSDN平台官方提供的学长联系方式的名片!温馨提示:文末有CSDN平台官方提供的学长联系方式的名片!作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO......
  • Python 实现 冒泡排序算法示例
    冒泡排序算法示例冒泡排序(BubbleSort)是一种简单的排序算法。它重复地遍历要排序的列表,比较相邻的元素,并交换它们的位置,如果它们的顺序错误。这个过程会重复进行,直到没有需要交换的元素为止,这时列表就已经排序完成。Python实现defbubble_sort(arr):n=len(arr)......
  • Python 中常用的算法
    1.排序算法用于将数据按特定顺序排列。冒泡排序(BubbleSort)选择排序(SelectionSort)插入排序(InsertionSort)快速排序(QuickSort)归并排序(MergeSort)堆排序(HeapSort)计数排序(CountingSort)基数排序(RadixSort)桶排序(BucketSort)2.搜索算法用于在数据集中查找特定元素。......
  • WxPython跨平台开发框架之前后端结合实现附件信息的上传及管理
    在使用wxPython开发跨平台应用时,结合后端实现附件信息的上传和管理是一种常见需求。WxPython跨平台开发框架是前后端分离的框架,前端采用的是WxPython+aiohttp 来构建跨平台的界面展示和处理,后端使用FastAPI,SQLAlchemy,Pydantic,Redis等技术构建的项目。后端数据库访问......
  • 【音乐探索新技能】用Python爬虫豆瓣音乐排行榜,发现你的下一首心头好!
    Hey,亲爱的音乐控们!你是否还在为找不到心仪的好音乐而头疼?是否还在为错过那些小众但超有味道的歌曲而遗憾?别急,今天我要给你们带来一个超级实用的小技巧——用Python爬虫豆瓣音乐排行榜,让你轻松成为音乐界的“先知”!步骤一:环境准备首先,你得有个Python环境。推荐使用Anacond......
  • Python入门教程 —— 安装软件
    1.安装python下载python访间Python官网:https:/www.python.org  安装python自定义安装,配置Python的环境变量。 选着安装路径,然后安装安装成功后,查看python版本:python-V2.安装 pycharm选着安装路径......
  • PaddleTS :一个易用的深度时序建模的Python库
    GitHub-PaddlePaddle/PaddleTS:AwesomeEasy-to-UseDeepTimeSeriesModelingbasedonPaddlePaddle,includingcomprehensivefunctionalitymoduleslikeTSDataset,Analysis,Transform,Models,AutoTS,andEnsemble,etc.,supportingversatiletasksliketim......
  • Linked_list in python
    Problem2.1:StoreDigits(100pts)Writeafunctionstore_digitsthattakesinanintegernandreturnsalinkedlistwhereeachelementofthelistisadigitofn.YoursolutionshouldruninLineartimeinthelengthofitsinput.Note:Youmaynotuse......
  • 使用python搭建网站的简明步骤
    选择 Web 框架Python 有许多 Web 框架,如 Flask、Django 等。Flask 是一个轻量级框架,适合初学者和小型项目;Django 是一个功能强大、内置组件丰富的框架,适合大型项目。以 Flask 为例进行介绍。首先,需要安装 Flask。可以使用pip命令安装,在命令行中执行pipinstallf......
  • 从零开始的Python世界生活——语法基础先导篇(Python小白零基础光速入门上手)
    从零开始的Python世界生活——语法基础先导篇(Python小白零基础光速入门上手)1.准备阶段1.1下载并安装Python1.1.1下载步骤:访问Python官方网站:点击这里下载Python在页面上,选择适合你操作系统的Python版本(Windows、macOS或Linux)。点击下载按钮,开始下载安装程序。1.1.2安......