Saturday, February 7, 2015

Week #5: Tracing recursion

Week #5: Tracing recursion


We have just learned how to trace recursive functions and write simple recursive function by ourselves in week 4. It is very interesting to trace a recursive function. In the procedure, we need to trace the recursion from the simplest case. And what cases we have trace before can be used as results in the new and harder cases. 

Just like the example in the lab:

I think that one of the difficulty in my lab is to find the function want to do with the attribute. We may easily trace a function case by case by using the result we have get in previous cases. But how can we know what the function want to do? I think we need to focus on what we need to do with the next case in the tracing. For example, we have traced the first 3 cases: nd('ox'), nd([]), and nd([1, 2, 3]). Now for nd([1, [2, 3], 4]), we use the result that  a int is just to return 0 and a list without elements of lists is just to return 1, and we find the max of the nd(elements in the list), and then + 1 at the end.  It is surprising to find that we just to add one if there is a '[]'. So we find the purpose of the function is just to find the number of nest in a nested-list.


Another problem I faced in the lab was how to write a recursion on my own. For example the length function. How to write recursion? I find it simple after analyze what need to be use time by time in our function. The simplest case in length is when L is not a list, then have: if not isinstance(L, list): return 0. Otherwise, we need to compare len(L) and length of the sublists of L, i.e. len(L) and length(x) for x in L. So we need to write the function as:else: return max(len(L), max([length(x) for x in L])). Then the recursion is written! So interesting, isn't it?

Recommend: http://computersciencemaggie.blogspot.ca/2015/03/summary-of-object-oriented-programming.html?showComment=1426384453547
Same idea as me, but much more specific processes are provided in this slog.

No comments:

Post a Comment