2015-09-13 52 views
0

如何找出python中表达式的深度?我写的代码很适合像[[1,2],[1,2,[3,6,54]]输入,而不是那些象depth (['+', ['expt', 'x', 2], ['expt', 'y', 2]]) => 2depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4使用Python表达式的深度

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) 
+0

可能重复[计数“深度”或最深层次的嵌套列表去(http://stackoverflow.com/questions/6039103/counting-deepness-或最深层次的嵌套列表去) –

+0

在我的代码我有深入的地方的FN,我忘了编辑它之前发布在这里.. –

回答

1

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

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 
+0

事实证明,它确实使用递归。原文中'fn'的含义是'深度',即函数的名称。 –

+0

是的fn是为了深入 –