Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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)</p> <pre><code>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) &gt; 0: return 1 + max(nesting) return 1 </code></pre> <p>Now lets make a list with the depth of three:</p> <pre><code>l=[[1,2,3],[1,2,[4]],'asdfg'] </code></pre> <p>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)</p> <p>Lets run this code:</p> <pre><code>&gt;&gt;&gt; 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 </code></pre> <p>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. </p> <p>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. </p> <p>If you still have problem getting it, try to add more <code>print</code> statements or other variables to the function and watch them carefully and eventually you'll get it. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload