在Python中以列表形式返回树的分支
我正试图用Python编写一个递归函数,它以列表的形式返回树的分支,给定分支的深度或最大和。我真的很沮丧。也许有更简单的类或生成器实现?下面是我想要实现的函数行为的详细描述在Python中以列表形式返回树的分支,python,function,class,tree,Python,Function,Class,Tree,我正试图用Python编写一个递归函数,它以列表的形式返回树的分支,给定分支的深度或最大和。我真的很沮丧。也许有更简单的类或生成器实现?下面是我想要实现的函数行为的详细描述 func(data, depth) '''Accepts a list with numbers > 0 and depth, i.e. max elements per list; returns each branch of a tree''' ----------Examples--------
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中,可以按如下方式执行:
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源代码。谢谢,欢迎。我在帖子上附加了一个简单的实现。