Saturday, 1 March 2014

Week7

    Recursion.

    Recursion is the concept of reusing a function within itself repeatedly to solve problems. A common structure for recursion consists of a base case and a general case. A base case provides functions with conditions to exit and a general case contains recursive calls to solve smaller problems.  Let's take the function factorial as an example. The following is the code for this function:

    
    def factorial(n: int) -> int:
        if n == 1:
            return 1
        else:
            return (n * factorial(n-1)) 
     
    As you can see, there're two conditions in the function. In this case, the if condition is the base case and the else condition is the general case. The base case stops the recursion once the given integer reaches 1 (by the definition of factorial). The general case asks the function to call itself on a smaller input, (n-1) in this case. This problem seems pretty simple but it would be tedious if we have to write down every multiplier of the factorial of n. With adapting recursive structure, we avoid these troubles when building our codes.

    To me, recursion is such a powerful mechanism where the function would split the problem into smaller pieces and solve bits by bits automatically. By automatic, I mean humans are not required to specify the exact pieces (or procedures) for the codes. This mechanism saves tons of works when dealing with complicated algorithms and generally gives you a more elegant code. It might not be apparent to you at the first glance how recursion works. As I mentioned in an earlier post, the best way to understand recursion, it's to trace it by hand. I've done that and now I am used to think recursively.


--------------------------------------------

    My thoughts of the week.

    We did our midterm test this week. I would say this test was fair and diverse in its content. In this course, we haven't being writing codes as intensive as in 108. That made writing codes on paper a bit challenging for me. From this experience, I think I should practice more coding rather than merely studying the theoretical ideas from classes. 


No comments:

Post a Comment