Wednesday, February 11, 2015

Impressions of tracing recursion

     This week, i learn about the recursion. 
Recursion is a method of coding a problem, in which a function calls itself.
For example, finding a maximum element in a list. We already know the ‘max()’ function but it only works with a flat list (list whose elements are just number, not a list or nested list).
If i didn’t learn about the recursion method, i would approach this problem by making a empty list called ‘l’ and put all the element in the argument to 'l'. Then i will get a flat list even if the argument was a list of list of list of list… so on.
Since argument is turned into a flat list, now i can use ‘max()’ function.

    However, my function would be very long , complicated and messy.  
As you know, “Simple is better”.
Recursion method will help my function to be simpler. BUT, I have to check whether i can use recursion method in this problem first.

    Let’s say my argument was s = [1, 2, [4, 3], [5 ,2], 8, 7]
What i have to do is, finding the maximum element in the nested list so that i can get s = [1, 2, 4, 5, 8, 7]. Then i can use max() function from this point.
So the task is the same (which is finding a max) if i break the problem down into smaller and smaller subproblems. Now i confirm this problem can be applied to recursion.



    This problem was covered in my computer science lecture. So i will just post the solution here, 
     You will easily capture how simple the code is. 
     This is the beauty of recursion!!


2 comments:

  1. I liked how you approached a problem and gave a solution! I agree with your post.

    ReplyDelete
  2. I liked how you approached a problem and gave a solution! I agree with your post.

    ReplyDelete