0

I have tried this code to find depth of an expression.Could you tell me where I am going wrong and what I should do to get the correct answer.

k=0
m=0
def fn(x):
    global k,m
    if isinstance(x,(tuple,list))== False : return "xyz"
    if isinstance(x,(tuple,list))== True :
        k=k+1
        if k>m: m=k

        for i in x:
            print i
            print k
            if isinstance (i,(list,tuple)):
                fn(i)
            else:
                if k>1: k=m
                else:k=1




fn([[['x',[1,[8,9],2],'y',[7,6]]]])
print "depth is",m                
Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

0

The one-letter forest is too eye-boggling to follow easily; I can help you improve your debugging practices.

(1) You have print statements in a couple of useful places, but you should also label the output to make the trace more readable.

(2) Use good variable names. single-letter variables don't tell us much. For instance, 'k' tells me nothing of the purpose. I have no way of knowing whether "k=k+1" is in the right spot.

(3) Don't use global variables for your computations. If this is a recursive routine, then code it that way. Call it "list_depth"; it accepts a list and returns an integer, the depth of that object. The way you've written this, it seems to return "xyz" for an atom (what does "xyz" mean???) and some convoluted computation otherwise.

(4) Those paired "if" statements at the top show flawed logic. Test the type once: if it's a list/tuple, recur to find the depth; if not, return a depth of 1.

I hope this helps you simplify and improve your algorithm.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • One other detail: does an atom, such as a simple integer, have a depth of 0 or 1? Your code assumes that it's 1. That may be your critical problem. – Prune Sep 16 '15 at 00:19
0

Recently, I happened to come across this issue and couldn't find any definite guide. So I thought of leaving this answer for someone who might need it in the future.

I tried many alternatives and came up with this solution.

def depth(in_data, current_depth=0):
current_max_depth = 0
if isinstance(in_data, (list, tuple)):
    current_depth += 1
    for data  in in_data:
        d = depth(data, current_depth)
        if d > current_max_depth:
            current_max_depth = d
    return current_max_depth
return current_depth

In this code, every time the program returns true for isinstance() it increases the current depth by 1 and passes this current depth together with the new elements to the function again. When it returns false it returns back the current depth with no change. Then by storing and comparing the current depth we can find the maximum depth. I hope this helps.

Aman Srivastava
  • 1,007
  • 1
  • 13
  • 25
AfiJaabb
  • 316
  • 3
  • 11