Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Cumulative Mul: Write a function cumulative_mul that mutates the Tree t so that each node’s label becomes the product of its label

$
0
0

Write a function cumulative_mul that mutates the Tree t so that each node’s label becomes the product of its label and all labels in the subtrees rooted at the node.

Hint: Consider carefully when to do the mutation of the tree and whether that mutation should happen before or after processing the subtrees

class Tree:    def __init__(self, label, branches=[]):        for b in branches:            assert isinstance(b, Tree)        self.label = label        self.branches = list(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

My English may not explain my thoughts clearly, forgive me.I can get a rough idea of the structure, the basic idea use recursion is when it's leaf return the value and when it's a subtree return the product of the labels of the subtree. the structure happened layer to layer.But what confused me is how is works when you need to multiply two labels of subtrees.


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>