Вопрос в том, чтобы: определить функцию sprout_leaves, которая принимает дерево t и список значений vals. Он создает новое дерево, идентичное 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]]? Любая помощь будет очень признательна!