Here is a tree I have. I want to calculate how many internal nodes (non-leaf nodes) starting from any node in the tree.
The function that I have now can only count all that is below A which gives 10. But I only want those before the terminal node.
- eg. for A, it should be 4 (B, C, E, H)
- eg. for E, it should be 1 (H)
How can I modify my function to do that? Note that my data is very large so a recursive function would cause a stack overflow.
name employee
0 A B
1 A C
2 B D
3 C E
4 C F
5 E H
6 E I
7 H T
8 H U
9 H V
#collapse to dictionary
dict_a = {k: g["employee"].tolist() for k,g in em.groupby("name")}
dict_a
{'A': ['B', 'C'],
'B': ['D'],
'C': ['E', 'F'],
'E': ['H', 'I'],
'H': ['T', 'U', 'V']}
# recursive function to count lengths:
def total(k,connections):
if k not in connections:
return 0
# number of direct connections plus their connections:
return len(connections[k]) + sum(total(child_k, connections) for child_k in connections[k])
