Sunday, February 1, 2015

Recursion-Week 5


This week I learned a new function, called recursive function.

A recursive function is a function that calls itself. Recursion is a powerful tool for solving repetitive problems.Recursion is very useful since it eliminates the unnecessary code and increase the efficiency. During the lecture, we have been showed lots of examples about how the recursive functions work and trace the function from the basic cases, which usually is a non-list element. We then increased the depth of the argument and figured out what the recursive function did.

Here is an example of recursive function


def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
This is how to implement factorial by recursive function.

Base case: if n is 1, then factorial (1) will return 1
second: if n==2, then return 2*1=2
Third: if n==3, then return 3*2*1=3!
....


The lab exercises except for the last question were very similar to what we did in the question. We were ask to trace some recursive function. At first glance, it was very hard to tell what the function acutually did without tracing some few examples. I realized that it was a very good idea to write down as a side note  how the functions worked for each level of input. It would help me to have a generalization for the higher level case which was not able to be traced. The last question asked us to code a recursive function. My partner and I had a hard time with that. I tried type in the code that I thought it should be write, but all test cases failed. I hope that Danny will talk about how to code a recursive function next week in the lecture

That is what I have for this week.


**8

No comments:

Post a Comment