Wednesday, April 8, 2015

Week7 - Recursion

     Recursion is similar to a circle. Usually, programmers write the complete functions before using it, but in Recursion, functions can be used inside themselves before they are completed.
     Recursion is a way of programming or coding a function, in which a function calls itself one or more times in its body. It appears to me difficult to understand at the beginning. Thinking recursively is very important to this part. First of all, you need to make sure you have a start case which tells python what to do recursively. The start case is really important because it decides how the entire function works. 
     The start case usually claim the condition of where the variable is None or 0. Then it claims what will happen if the variable is not None. One example can be:


def node_count(root):
    if not root:
        return 0
    else:
        return 1 + sum([node_count(child) for child in root.children])

where it shows if root is None, the function returns the value "0" so every time when it runs to get to the end of the tree, it doesn't add another value to the answer.

Recursion is one of the best way to write functions so far. By writing codes recursively, it reduces a lot of work. It's also the fastest way to write.

No comments:

Post a Comment