Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/11.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 2.7 使用Python的表达式的深度_Python 2.7 - Fatal编程技术网

Python 2.7 使用Python的表达式的深度

Python 2.7 使用Python的表达式的深度,python-2.7,Python 2.7,如何在python中找到表达式的深度?我所写的代码对于像[[1,2]、[1,2]、[3,6,54]这样的输入非常有效,但对于深度(['+'、['expt'、[x',2]、'expt'、'y',2]=>2和深度('/'、('expt'、'x',5)、('expt'、('-'、('expt'、('expt'、'x',',2)、('/'、5、2))=>4 a=0 k=0 j=0 maxli=[] li =[[1,2],[1,2,[3,6,54]] # list whose depth is to b

如何在python中找到表达式的深度?我所写的代码对于像
[[1,2]、[1,2]、[3,6,54]
这样的输入非常有效,但对于
深度(['+'、['expt'、[x',2]、'expt'、'y',2]=>2
深度('/'、('expt'、'x',5)、('expt'、('-'、('expt'、('expt'、'x',',2)、('/'、5、2))=>4

a=0
k=0
j=0
maxli=[] 
li =[[1,2],[1,2,[3,6,54]] # list whose depth is to be found
#print len(li)

def depth(x):


    global a,k,j
    j=j+1
    print" j's value is ",j
    for i in x:

      for h in range(len(li)): # runs loop through the items of the list 
          if i== li[h]  : k=0  

      if isinstance(i,(tuple,list)) == True: #if we find that there is list
        k=k+1

      #  print "this is for item",i  
      #  print k
        depth(i) 

    a=k
    maxli.append(a) # putting the values of a in maxli

depth(li)
print "The depth of tree is :",max(maxli)

这里使用递归的正确方法是通过函数的返回值,而不是通过操纵全局变量。您可以定义如下深度函数:

def is_list(x):
    return hasattr(x,'__getitem__') and type(x) != str

def depth(l):
    if not is_list(l): return 0
    maxdepth = 0
    for elem in l:
        maxdepth = max(maxdepth, depth(elem))
    return maxdepth + 1

在我的代码中可能有重复的,我用深度代替fn,我在这里发布之前忘记了编辑它。事实证明,它确实使用了递归。原始帖子中的
fn
是指
depth
,函数的名称。