python3.x版本 机器学习实战《Machine Learing in Action》——第三章python中叶子数和树的深度代码

python3.x版本下,在用example_dict.keys()或者example_dict.values()取出字典中对应的键值时,取出的值总是会带有前缀。

python2.x版本的不存在这个问题,可以直接使用书中的代码

以下是python3.x版本代码:

def getNumLeafs(myTree): # python3 版本 返回叶子数
    numLeafs = 0
    secondDict = list(myTree.values())
    for key in range(len(secondDict[0])):
        if type(secondDict[0][key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
            numLeafs += getNumLeafs(secondDict[0][key])
        else:   numLeafs +=1
    return numLeafs

def getTreeDepth(myTree): # python3 版本 返回树的深度,即多少层
    maxDepth = 0
    secondDict = list(myTree.values()) # 去掉dict_values类名
    for key in range(len(secondDict[0])):
        if type(secondDict[0][key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
            thisDepth = 1 + getTreeDepth(secondDict[0][key])
        else:   thisDepth = 1
        if thisDepth > maxDepth: maxDepth = thisDepth
    return maxDepth

对不起,各位看官,上面的代码有点投机取巧了
由于字典的key正好是0,1,所以可以secondDict[0][key]这样索引
下面我将进行修改,使得代码普适性更好

def getNumLeafs(myTree): # python3 版本 返回叶子数
    numLeafs = 0
    secondDict = list(myTree.values())[0]
    xinkeys=list(secondDict.keys())
    for key in range(len(secondDict)):
        if type(secondDict[xinkeys[key]]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
            numLeafs += getNumLeafs(secondDict[xinkeys[key]])
        else:   numLeafs +=1
    return numLeafs
    
def getTreeDepth(myTree): # python3 版本 返回树的深度,即多少层
    maxDepth = 0
    secondDict = list(myTree.values())[0] # 去掉dict_values类名
    xinkeys=list(secondDict.keys())
    for key in range(len(secondDict)):
        if type(secondDict[xinkeys[key]]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
            thisDepth = 1 + getTreeDepth(secondDict[xinkeys[key]])
        else:   thisDepth = 1
        if thisDepth > maxDepth: maxDepth = thisDepth
    return maxDepth
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页