加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 寻找表达深度的递归

发布时间:2020-12-16 23:40:54 所属栏目:Python 来源:网络整理
导读:我试图使用递归来查找“表达式”的深度,即有多少层嵌套元组:例如, depth(('+',('expt','x',2),'y',2))) = 2depth(('/',5),('-',1),('/',5,2)))) = 4 基本上,我认为我需要检查(从out到in)为每个元素作为元组的实例,然后如果是,则递归调用depth函数.但我需要
我试图使用递归来查找“表达式”的深度,即有多少层嵌套元组:例如,
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读