Search code examples
pythonrecursionnesteddepth

having trouble understanding this code


I just started learning recursion and I have an assignment to write a program that tells the nesting depth of a list. Well, I browsed around and found working code to do this, but I'm still having trouble understanding how it works. Here's the code:

def depth(L) :
    nesting = [] 
    for c in L:
        if type(c)  == type(nesting) :
            nesting.append(depth(c)) 
    if len(nesting)  > 0:
        return 1 + max(nesting)
    return 1

So naturally, I start to get confused at the line with the append that calls recursion. Does anyone have a simple way of explaining what's going on here? I'm not sure what is actually being appended, and going through it with test cases in my head isn't helping. Thanks!

edit: sorry if the formatting is poor, I typed this from my phone


Solution

  • Let me show it to you the easy way, change the code like this: (### are the new lines I added to your code so you can watch what is happening there)

    def depth(L) :
        nesting = []
        for c in L:
            if type(c)  == type(nesting) :
                print 'nesting before append', nesting ###      
                nesting.append(depth(c))
                print 'nesting after append', nesting ###
        if len(nesting)  > 0:
            return 1 + max(nesting)
        return 1
    

    Now lets make a list with the depth of three:

    l=[[1,2,3],[1,2,[4]],'asdfg']
    

    You can see our list has 3 element. one of them is a list, the other is a list which has another list in itself and the last one is a string. You can clearly see the depth of this list is 3 (i.e there are 2 lists nested together in the second element of the main list)

    Lets run this code:

    >>> depth(l)
    nesting before append []
    nesting after append [1]
    nesting before append [1]
    nesting before append []
    nesting after append [1]
    nesting after append [1, 2]
    3
    

    Piece of cake! this function appends 1 to the nesting. then if the element has also another list it appends 1 + maximum number in nesting which is the number of time function has been called itself. and if the element is a string, it skips it.

    At the end, it returns the maximum number in the nesting which is the maximum number of times recursion happened, which is the number of time there is a list inside list in the main list, aka depth. In our case recursion happened twice for the second element + 1=3 as we expected.

    If you still have problem getting it, try to add more print statements or other variables to the function and watch them carefully and eventually you'll get it.