递归以找到表达的深度

时间:2012-09-11 16:35:44

标签: python recursion tracking depth

我正在尝试使用递归来查找“表达式”的深度,即有多少层嵌套元组:例如,

depth(('+', ('expt', 'x', 2), ('expt', 'y', 2))) => 2

depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 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

关于如何做到这一点的好方法的想法?

5 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

仅限伪代码(不保证编译,更不用说运行):

dep depth(expr):
  if not isinstance(expr, tuple):
    return 0
  else:
    mdepth = 0
    for x in range(0, len(expr)):
      d = depth(expr[x])
      if d > mdepth:
        mdepth = d
    return mdepth+1

答案 2 :(得分:0)

在这里,试试这个 - 它是一个函数式编程解决方案,采用Lisp,Haskell等语言编写时使用的样式。

def depth(exp):
    if not exp:                         # the tuple is empty
        return 0                        #return 0
    elif not isinstance(exp[0], tuple): # first element is not a tuple
        return depth(exp[1:])           # traverse the rest of elements
    else:  # depth is 1 + depth of first tuple + depth of rest of elements
        return 1 + max(depth(exp[0]), depth(exp[1:]))

答案 3 :(得分:0)

你可以试试这个,

def depth(expr):
count = 0
if not isinstance(expr,tuple):
    return 0 
else:
    count = 1
    count1 = 0
    for e in expr:
        count1 = 1 + depth(e)
        count = max(count1,count)
return count

答案 4 :(得分:0)

您可以在遍历子表达式时跟踪最后的最大深度。

def depth(expr):
    # base case
    if not isinstance(expr, tuple):
        return 0
    # if it is a tuple, we've at least depth of 1
    max_depth = 1
    # If any sub-expression is deeper, update max_depth
    for elem in expr:
        elem_depth = 1 + depth(elem)
        if elem_depth > max_depth:
            max_depth = elem_depth
    return max_depth