0

How do I find out the depth of an expression in python? The code I've written works well for inputs like [[1,2],[1,2,[3,6,54]] but not for ones like depth (['+', ['expt', 'x', 2], ['expt', 'y', 2]]) => 2 and depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 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)
Alex A.
  • 5,466
  • 4
  • 26
  • 56
  • possible duplicate of [Counting "deepness" or the deepest level a nested list goes to](http://stackoverflow.com/questions/6039103/counting-deepness-or-the-deepest-level-a-nested-list-goes-to) – Alex A. Sep 13 '15 at 03:26
  • In my code i had depth in place of fn,i forgot to edit it before posting here.. – Shubam Jayswal Sep 13 '15 at 04:38

1 Answers1

2

The correct way to utilize recursion here is via the return value of the function, not by manipulating global variables. You could define a depth function like this:

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
feersum
  • 658
  • 4
  • 11
  • As it turns out, it does use recursion. What was `fn` in the original post was meant to be `depth`, the name of the function. – Alex A. Sep 13 '15 at 04:42