简体   繁体   English

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

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

I'm trying to write a recursive function in Python that returns branches of a tree as lists, given depth or max_sum of a branch. 我正在尝试用Python编写一个递归函数,该函数以给定深度或分支的max_sum返回列表的树分支。 I'm really frustrated by this. 我对此感到非常沮丧。 Maybe there are easier implementations with classes or generators? 也许使用类或生成器更容易实现? Below is the detailed description of the function behaviour i want to achieve. 下面是我要实现的功能行为的详细说明。

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]]

Picture for the second example 第二个例子的图片

Picture for the third example 第三个示例的图片

Here's the code i wrote, which works only for the first example, it's horrible and i really feel ashamed of it :/ I tried dozens of approaches using classes and generators, but i'm not very familiar with those and the code only returned half of the options even for the first example. 这是我编写的代码,仅适用于第一个示例,这太可怕了,我为此感到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)

I don't see why you want to relate this to traversing a tree. 我不明白为什么要将此与遍历树相关联。 Your task basically is just generating all permutations (with replacement) - which is identical to the Cartesian product with a fixed set - of a given length over a set of numbers. 您的任务基本上只是生成所有排列(带有替换),该排列与一组固定长度的给定长度的笛卡尔乘积相同。

In Python you can do it as follows: 在Python中,您可以执行以下操作:

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

This would eg output your third example. 例如,这将输出您的第三个示例。 Just note that each output is a tuple and not a list - so you may want to convert them. 请注意,每个输出都是一个元组而不是一个列表-因此您可能要转换它们。

The simplest implementation would probably work like this: 最简单的实现可能是这样的:

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)

Output: 输出:

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