Ish*_*108 6 python recursion tracking depth
我试图使用递归来找到"表达式"的深度,即有多少层嵌套元组:例如,
depth(('+', ('expt', 'x', 2), ('expt', 'y', 2))) => 2
depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4
Run Code Online (Sandbox Code Playgroud)
基本上,我认为我需要检查(从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
Run Code Online (Sandbox Code Playgroud)
想一个好方法来解决这个问题?
Dav*_*son 11
你在正确的轨道上,而不是寻找"总"深度count += 1 + depth(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(('+', ('expt', 'x', 2), ('expt', 'y', 2)))
# 2
print depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2))))
# 4
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3685 次 |
| 最近记录: |