2015年4月5日星期日

Revist recursion

Today, I read my previous opinion about recursion. I found many misunderstanding at that time. I was thinking that recursion is something similar to a loop. That's totally wrong. Maybe iteration is more like a loop than recursion. What I was right at that time is about its cleanness and tidiness. Recursion is something that weird but beautiful. A recursive function is like a function or algorithm for all parts in a recursive structure such as tree. But as I learn more, I found it's not true that we can always write what a function needs to do in one function, maybe that's because what it needs to do becomes more complicated compare with the algorithms we learnt before. Just like some functions in Assignment 3. I found that, some functions in Assignment have recursive part and non-recursive part in one function. And since recursive part would be reached every time, we can not write the non-recursive part and recursive part together. For example, I need a empty list at the beginning to be used to append elements, and the algorithm of appending elements is recursive. If I put assignment statement in recursive part. At each step, an empty list will appear and there is no way to append it to the original one. So instead, I assign an empty list in the function and write a help function which is recursive to let it do its job, and then I pass the list in recursive function parameter. The helper function do nothing but appending suitable elements to the list in parameter.
I feel as I learn more about recursion, I feel more uncertain about whether recursive part has a typical format. I thought recursive functions would always be like:
if XXXXX:
    XXXXXX
else:
    XXXXXX
However now I know it is not like that. Recursive functions do have if statement and else statement, but they depend upon the node it is working on is a leaf or node. Sometimes we do not need to add an else statement because we need it to do something even after it finishes if statement. For example, the if statement turns a leaf into a node and then if we want to do something to the nodes, we don't need to add an else statement.

没有评论:

发表评论