Thursday, April 2, 2015

Revisit an earlier SLOG posting of myself

Recursion has been a pretty important part of the course, with many different examples being given in class. In Assignment 2 and Assignment 3, we are required to use recursion to implement the functions. We spent lots of time discussing this topic in class. Thus, I prefer to revisit my earlier post on recursion so that l can review this important topic and strength the knowledge 

In my earlier post, l said that l had problems with understanding recursion. 
Here is the former code that l don't understand.

def depth(L):
    ''' (list or non-list) -> int

    Return 0 if L is a non-list, or 1 + maximum
    depth of elements of L, a possibly nested
    list of objects

    >>> depth(3)
    0
    >>> depth([])
    1
    >>> depth([1, 2, 3])
    1
    >>> depth([1, [2, 3], 4])
    2
    '''
    if isinstance(L, list):
        return 1 + max([depth(x) for x in L])
    else: # L is not a list
        return 0

Now, l think this is not difficult to understand this piece of code. But l still have problems with  recursion. One thing that I found definitely helped me understand this better was simply tracing very small test cases and writing by hand what happens at each step.
Recursive functions make the code look clean and elegant, but hard to understand. l find that there has some structures to write recursive function. it might help me to understand recursion function deeply.
  1. if xxxxxxx:
          return  xxxx     #it’s base case
      else:
          xxxxx    #  calling  the function
  The recursive function previously shown belongs to this kind of structure.

 2. 
     I would like to show this kind of structure by using the code l wrote from Assignment 3.
     It’s always one line.

  def node_count(root):
    ''' (GameStateNode) -> int
     
    Return the number of nodes in the tree rooted at root.

    >>> s = SubtractSquareState('p1', current_total = 6)
    >>> root = GameStateNode(s)
    >>> root.grow()
    >>> node_count(root)
    13
    '''
    return 1 + sum([node_count(x) for x in root.children])



Overall , I am really enjoying learning python, although it is hard for me to master the material. Practicing to write recursive functions is an important part in developing my skills in applying recursion effectively as well as  helping grow my knowledge base in python. Assignment 2 and 3 are good practices for me to grasp the content of recursion as well as the labs.  l find that he more you practice, the more you gain.

Many other SLOGs that I have read from other classmates seem to agree with the
idea that the more you practice the more you grasp the material. They think that the good way to understand the recursive function is trace very small test cases and write by hand what happens at each step, it's just the same like what l think.