【问题标题】:try to build Recursive data structures on python尝试在 python 上构建递归数据结构
【发布时间】:2021-04-17 09:27:15
【问题描述】:

大家好,我的课程有一个任务,我需要构建一个函数,将给定的树(树)表示为元组返回一棵新树(树的显示)

class Tree(object):
    def __init__(self, value, nodes=None):
        self.value = value
        self.nodes = nodes

    def __repr__(self):
        if self.nodes:
            return 'Tree({0},{1})'.format(self.value, repr(self.nodes))
        return 'Tree({0})'.format(self.value)


def BuildTree(tree):
    if type(tree) != tuple:
        return Tree(tree)
    <3 >
    return Tree("here i need to put the height" ,list(map(BuildTree, tree)))


t1 = BuildTree((((1, 2), 3), (4, (5, 6))))
print(t1)

直到现在我只得到这样的结果。

树([树([树([树(1),树(2)]),树(3)]),树([树(4),树([树(5),树(6 )])])])

但我不知道我计算每个内部节点的高度

我有这张描述新树构造的图片。 所以绿色的数字是高度,红色的数字是我在元组中的值

所以新树的正确输出是这样的。

树(3,[树(2,[树(1,[树(1),树(2)]),树(3)]),树(2,[树(4),树(1 ,[树(5), 树(6)])])])

【问题讨论】:

    标签: python python-3.x recursion tree height


    【解决方案1】:

    让我们用简单的语言描述height -

    1. 空树的高度为0
    2. 非空树的高度是1加上子节点的最大高度

    我们可以用数学归纳法来写这个

    1. 如果输入树t为空,则返回空结果
    2. (感应)t 不为空。已解决子问题的maxt.nodes 加 1,然后返回
    def height (t):
      if not t:
        return 0                                    # (1)
      else:
        return 1 + max(height(n) for n in t.nodes)  # (2)
    

    但是,要使其正常工作,您需要初始化 nodes=[] 而不是 nodes=None。否则,它会使您的程序更加复杂 -

    1. 如果输入树t为空,则返回空结果
    2. (感应)t 不为空。如果t.nodes 为空,则已到达叶节点;返回 1
    3. (感应)t 不为空,t.nodes 不为空。已解决子问题的maxt.nodes 加 1,然后返回
    def height (t):
      if not t:
        return 0                                   # (1)
      elif not t.nodes:
        return 1                                   # (2)
      else:
        return 1 + max(height(n) for n in t.nodes) # (3)
    

    【讨论】:

    • 但我需要在一行(管道)中执行此操作而不调用任何函数。你可以使用 "lambda , map, filter, max, sum" 你可以使用你想要的但不能创建函数...
    • 节点需要保持无...如果你能像高度函数一样创建一行,那就太好了
    【解决方案2】:
    h = lambda x: 1 + max(list(map(h, x))) if type(x) == tuple else 0
    

    【讨论】:

    • 虽然这可能是 OP 问题的答案,但 StackOverflow 上的纯代码答案是 discouraged。请考虑在提供的代码中添加一些解释,因为这将使 OP 和未来的访问者都受益
    猜你喜欢
    • 2017-08-06
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多