[英]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.