📜  Python – 叶和非叶节点字典

📅  最后修改于: 2022-05-13 01:55:50.357000             🧑  作者: Mango

Python – 叶和非叶节点字典

有时,在使用Python时,我们可能会遇到需要处理以字典形式表示的图形数据的问题。在此,我们可能需要检查所有叶节点和非前导节点。这类问题在机器学习算法中有直接应用。让我们讨论一种可以执行此任务的方式。

方法:使用递归 + isinstance() + 循环
上述功能的组合可以用来解决这个问题。在此,我们使用递归对内部嵌套进行递归,并使用 isinstance() 按值类型检查叶子或非叶子。

Python3
# Python3 code to demonstrate working of
# Leaf and Non-Leaf Nodes Dictionary
# Using recursion + isinstance() + loop
 
def hlpr_fnc(dict1, res = {'non-leaf':0, 'leaf':0}):
     
    #res['non-leaf'] += 1  
    nodes = dict1.keys()
    for node in nodes:
      subnode = dict1[node]
      if isinstance(subnode, dict):
        res['non-leaf'] += 1
        hlpr_fnc(subnode, res)
      else:
        res['leaf'] += 1 
    return res
 
# initializing dictionary
test_dict = {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Leaf and Non-Leaf Nodes Dictionary
# Using recursion + isinstance() + loop
res = hlpr_fnc(test_dict)
     
# printing result
print("The leaf and Non-Leaf nodes : " + str(res))


输出:

The original dictionary : {'a': {'b': 1, 'c': {'d': {'e': 2, 'f': 1}}, 'g': {'h': {'i': 2, 'j': 1}}}}
The leaf and Non-Leaf nodes : {'non-leaf': 5, 'leaf': 5}