0

Given a dataframe as follows:

  root subroot leaf  value  
0    A      B1   C1     58  
1    A      B1   C2      7  
2    A      B2   C1      0 
3    A      B2   C2     20 

and code as follows:

from collections import deque

class Node:
    def __init__(self, name, weight, children):
        self.name = name
        self.children = children
        self.weight = weight
        self.weight_plus_children = weight

    def get_all_weight(self):
        if self.children is None:
          return self.weight_plus_children
        for child in self.children:
            self.weight_plus_children += child.get_all_weight()
        return self.weight_plus_children

    
def print_tree(root: Node):
    queue = deque()
    queue.append(root)
    while queue:
        front = queue.popleft()
        print('{} = {}'.format(front.name, front.weight_plus_children))
        if front.children:
            for child in front.children:
                if child is not None:
                    queue.append(child)


leaf1 = Node('C1', 58, None)
leaf2 = Node('C2', 7, None)
leaf3 = Node('C1', 0, None)
leaf4 = Node('C2', 20, None)

subroot = Node('B1', 0, [leaf1, leaf2])
subroot1 = Node('B2', 0, [leaf3, leaf4])

root = Node('A', 0, [subroot, subroot1])

root.get_all_weight()

print_tree(root)

How could I pass leaf values from df to the following leaf dynamically?

The main ideas I'm doing this is I want to read excel files and pass leaf values to the code:

leaf1 = Node('C1', 58, None)
leaf2 = Node('C2', 7, None)
leaf3 = Node('C1', 0, None)
leaf4 = Node('C2', 20, None)

We can filter input=1's rows with: df.loc[df['input'] == 1].

Output expected:

A = 85
B1 = 65
B2 = 20
C1 = 58
C2 = 7
C1 = 0
C2 = 20

Thanks for your kind help.

3
  • 1
    Can you tell what's the output for a sample input? Commented Jul 15, 2020 at 6:36
  • I updated the the code part and output expected based on your previous solution. Commented Jul 15, 2020 at 6:42
  • I simplify the question, any ideas to solve this issue? Commented Jul 19, 2020 at 3:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.