【发布时间】: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