问题是:定义一个函数bud_leaves,该函数接受树t和值列表val。它会产生一棵与t相同的新树,但是每个旧叶节点都有一个新分支,每个分支对应vals
def sprout_leaves(t, vals):
"""Sprout new leaves containing the data in vals at each leaf in
the original tree t and return the resulting tree.
>>> t1 = tree(1, [tree(2), tree(3)])
>>> print_tree(t1)
1
2
3
>>> new1 = sprout_leaves(t1, [4, 5])
>>> print_tree(new1)
1
2
4
5
3
4
5
>>> t2 = tree(1, [tree(2, [tree(3)])])
>>> print_tree(t2)
1
2
3
>>> new2 = sprout_leaves(t2, [6, 1, 2])
>>> print_tree(new2)
1
2
3
6
1
2
"""
def tree(label, branches=[]):
"""Construct a tree with the given label value and a list of branches."""
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return [label] + list(branches)
def label(tree):
"""Return the label value of a tree."""
return tree[0]
def branches(tree):
"""Return the list of branches of the given tree."""
return tree[1:]
def is_tree(tree):
"""Returns True if the given tree is a tree, and False otherwise."""
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree(branch):
return False
return True
def is_leaf(tree):
"""Returns True if the given tree's list of branches is empty, and False
otherwise.
"""
return not branches(tree)
What I've tried so far is:
def sprout_leaves(t, vals):
if is_leaf(t):
t += [vals]
else:
new_branches = []
for branch in branches(t):
if is_leaf(label(branch)):
for j in range(0, len(label(branch))):
[label(branch)[j]] += [vals]
new_branches += [label(branch)[j]]
**????**
return t
我一直坚持用修改后的分支替换树的原始分支。 例如,如果原始树是[1,[2,3]],而修改后的分支是[2,[4,5],3,[4,5]],我应该怎么做才能重新放置[2, [4,5],3,[4、5]]? 任何帮助将不胜感激!