【问题标题】:Returning branches of a tree as lists in Python在 Python 中将树的分支作为列表返回
【发布时间】:2017-01-22 15:25:45
【问题描述】:

我正在尝试在 Python 中编写一个递归函数,它以列表的形式返回树的分支,给定分支的深度或 max_sum。我对此感到非常沮丧。也许使用类或生成器有更简单的实现?下面是我想要实现的功能行为的详细描述。

func(data, depth)
'''Accepts a list with numbers > 0 and depth, i.e. max elements per list; 
   returns each branch of a tree'''    

----------Examples--------------
Input:  func([2, 1], depth=2)
Output: [[2, 2], [2, 1], [1, 2], [1, 1]]

Input:  func([3, 2, 1], depth=2)
Output: [[3, 3], [3, 2], [3, 1]
         [2, 3], [2, 2], [2, 1]
         [1, 3], [1, 2], [1, 1]]

Input:  func([2, 1], depth=3)
Output: [[2, 2, 2], [2, 2, 1], [2, 1, 2], [2, 1, 1],
         [1, 2, 2], [1, 2, 1], [1, 1, 2], [1, 1, 1]]

第二个例子的图片

第三个例子的图片

这是我编写的代码,仅适用于第一个示例,它太可怕了,我真的为它感到羞耻:/ 我尝试了几十种使用类和生成器的方法,但我对这些和代码不是很熟悉即使对于第一个示例,也只返回了一半的选项。

tree = []
node_list = [2, 1]

def make_branch(depth=2, branch=None, d={0:2, 1:1}, switch=False, count=0):
    #print(count)

    if branch is None:
        branch = []

    for i in range(2):
        #print(i)
        if switch:
            branch.append(d[i+1]) 
            switch=False
        else:
            branch.append(d[i])

        if len(branch) >= depth:
            tree.append(branch)
            print(branch)
            return

        make_branch(count= count + 1, branch=branch)
        #print(-count)
        branch = branch[:-1]


for i in range(len(node_list)):
    if i % 2 == 0:
        make_branch()
    else:
        make_branch(switch=True)

print(tree)

【问题讨论】:

    标签: python function class tree


    【解决方案1】:

    我不明白您为什么要将这与遍历树联系起来。您的任务基本上只是在一组数字上生成给定长度的所有排列(带替换) - 这与具有固定集合的笛卡尔积相同。

    在 Python 中你可以这样做:

    import itertools
    for i in itertools.product([1,2], repeat=3):
      print i
    

    这将是例如输出你的第三个例子。请注意,每个输出都是一个元组而不是一个列表 - 所以您可能需要转换它们。

    最简单的实现可能是这样的:

    def prod(lst, depth, buf=''):
        if depth == 0:
            print buf
            return
        for elem in lst:
            prod(lst, depth - 1, buf + str(elem))
    
    prod([1,2], 3)
    print 
    prod([1,2,3], 2)
    

    输出:

    111
    112
    121
    122
    211
    212
    221
    222
    
    11
    12
    13
    21
    22
    23
    31
    32
    33
    

    【讨论】:

    • 哇!我不知道为什么。我只是专注于使用递归和树的特定实现,并没有看到其他方法。首先要检查 itertools 源代码。谢谢。
    • 欢迎。我在帖子中附加了一个简单的实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2011-03-18
    • 2013-05-25
    相关资源
    最近更新 更多