python – 寻找表达深度的递归
发布时间:2020-09-26 00:29:44  所属栏目:Python  来源:互联网 
            导读:我试图使用递归来查找“表达式”的深度,即有多少层嵌套元组:例如, depth((+, (expt, x, 2), (expt, y, 2))) = 2depth((/, (expt, x, 5), (expt, (-, (expt, x, 2), 1), (/, 5, 2)))) = 4 基本上,我认为我需要检查(从out到in)为每个元
                
                
                
            | 
                         我试图使用递归来查找“表达式”的深度,即有多少层嵌套元组:例如, depth(('+',('expt','x',2),'y',2))) => 2
depth(('/',5),('-',1),('/',5,2)))) => 4 
 基本上,我认为我需要检查(从out到in)为每个元素作为元组的实例,然后如果是,则递归调用depth函数.但我需要找到一种方法来确定哪一组递归调用具有最大的深度,这就是我被卡住的地方.这是我到目前为止所拥有的: def depth3(expr):
    if not isinstance(expr,tuple):
        return 0
    else:
        for x in range(0,len(expr)):
            # But this doesn't take into account a search for max depth
            count += 1 + depth(expr[x])
    return count 
 想一个好方法来解决这个问题? 解决方法你是在正确的轨道上,而不是用count = 1深度(expr [x])找到“总”深度,使用max查找最大值: def depth(expr):
    if not isinstance(expr,tuple):
        return 0
    # this says: return the maximum depth of any sub-expression + 1
    return max(map(depth,expr)) + 1
print depth(("a","b"))
# 1
print depth(('+',2)))
# 2
print depth(('/',2)))) 
# 4                        (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
