Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 求表达式深度的递归_Python_Recursion_Tracking_Depth - Fatal编程技术网

Python 求表达式深度的递归

Python 求表达式深度的递归,python,recursion,tracking,depth,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函数。但我需要找到一种方法,找出哪一组

我试图使用递归来找到一个“表达式”的深度,即嵌套元组有多少层:例如

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

如何找到一个好方法?

您的思路是正确的,但不是使用
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(('+', ('expt', 'x', 2), ('expt', 'y', 2)))
# 2
print depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) 
# 4
仅伪代码(不保证编译,更不用说运行):

深度(expr): 如果不是isinstance(表达式,元组): 返回0 其他: mdepth=0 对于范围(0,len(expr))内的x: d=深度(expr[x]) 如果d>mdepth: mdepth=d 返回mdepth+1
在这里,试试这个——这是一个函数式编程解决方案,与用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:]))
你可以试试这个

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

在遍历子表达式时,可以简单地跟踪最后一个最大深度

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

通过像
depth(expr,layers)
这样的方法传递一个变量,并从1开始调用,对于其中的每个表达式,调用
depth
increment layers。好的,很有趣。。但对于最后一个示例(返回3而不是4),它似乎不起作用?为了更好地理解这一点,您如何能够在不将每个元组分解为每个元素的情况下实现这一点(就像for循环那样)?上一个示例出错是什么意思?我得到4(你复制粘贴正确吗?)。另外:
map
函数对元组的每个元素都进行操作
map(depth,expr)
的意思是“将函数
depth
应用到
expr
.Oops.对不起,我测试时运行的是一个旧版本的函数!好的,谢谢!不知道map函数是如何工作的,我是从其他语言来到python的。非常感谢!
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