繁体   English   中英

返回树的分支作为Python中的列表

[英]Returning branches of a tree as lists in Python

我正在尝试用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]]

第二个例子的图片

第三个示例的图片

这是我编写的代码,仅适用于第一个示例,这太可怕了,我为此感到really愧:/我尝试了使用类和生成器的数十种方法,但是我对这些方法不太熟悉,并且代码只返回了一半甚至第一个示例的选项。

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中,您可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM