我试图使用递归来查找“表达式”的深度,即有多少层嵌套元组:例如,
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
