I have a dictionary which contains subdictionaries. It's a decision tree with nodes, some leaf nodes and some non-leaf nodes. How can I count each of these given the dictionary?
For example:
{'Outlook': {'Overcast': 'Yes', 'Rain': {'Wind': {'Strong': 'No', 'Weak': 'Yes'}}, 'Sunny': {'Humidity': {'High': 'No', 'Normal': 'Yes'}}}}
This generates a tree like below:
In it are three non-leaf nodes and five leaf nodes. I have a general idea of how I can do it:
def count(d):
a, b = 0, 0 # non-leaf nodes and leaf nodes
for key, value in d.items():
if isinstance(value, dict):
a += 1
# some recursive call on value
else:
b+= 1
return a, b
But I'm not sure how to organize the recursive call. Is there a built-in method?
