编写一个函数cumulative_mul,它会改变Tree t,使每个节点的标签成为其标签与以该节点为根的子树中所有标签的乘积。 提示:仔细考虑何时对树进行变异以及该变异是否应该在处理子树之前或之后发生 类树: def init(自身,标签,分支=[]): 对于分支中的 b: 断言 isinstance(b, 树) self.label = 标签 self.branches = 列表(分支)
def is_leaf(self):
return not self.branches
类树: def init(自身,标签,分支=[]): 对于分支中的 b: 断言 isinstance(b, 树) self.label = 标签 self.branches = 列表(分支)
def is_leaf(self):
return not self.branches
def cumulative_mul(t):
"""Mutates t so that each node's label becomes the product of all labels in
the corresponding subtree rooted at t.
>>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])
>>> cumulative_mul(t)
>>> t
Tree(105, [Tree(15, [Tree(5)]), Tree(7)])
>>> otherTree = Tree(2, [Tree(1, [Tree(3), Tree(4), Tree(5)]), Tree(6, [Tree(7)])])
>>> cumulative_mul(otherTree)
>>> otherTree
Tree(5040, [Tree(60, [Tree(3), Tree(4), Tree(5)]), Tree(42, [Tree(7)])])
"""
"*** YOUR CODE HERE ***"
if t.is_leaf():
return
for b in t.branches:
cumulative_mul(b)
if isinstance(b, Tree):
t.label *= b.label
我的英语可能无法清楚地表达我的想法,请原谅我。 我可以大致了解结构,使用递归的基本思想是当它的叶子返回值时,当它是子树时返回子树标签的乘积。结构层层发生。但让我困惑的是,当您需要将子树的两个标签相乘时,它是如何工作的。
要处理来自不同
labels
的subtrees
的乘法,您可以先计算每个product
的labels
的subtree
,然后将其与当前的node's label
相乘。
# class to represent the object for problem
class Tree:
def __init__(self, label, branches=[]): # init function to create object
self.label = label
self.branches = branches
def is_leaf(self): # check the 'self' is leaf
return not self.branches
# function to manipulate with object 'Tree'
def cumulative_mul(t):
if t.is_leaf(): # check by using method
return
subtree_product = 1 # Initialize product for the current subtree
for b in t.branches: # cycle
cumulative_mul(b)
if isinstance(b, Tree): # check
subtree_product *= b.label # Multiply labels of subtrees
t.label *= subtree_product # Multiply the current node's label by the subtree product
# Test cases for problem
t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])
cumulative_mul(t) # run test cases
print(t.label) # Output: 105
otherTree = Tree(2, [Tree(1, [Tree(3), Tree(4), Tree(5)]), Tree(6, [Tree(7)])])
cumulative_mul(otherTree) # run test cases
print(otherTree.label) # Output: 5040