Sunday, 2 March 2014

Week 7 recursion

    Through the past couple weeks we have been study on Recursion, which is basically to repeat a recursive procedure  multiple times. The idea that have been introduced to the class was to repetitively call a recursive function until  a "base case" is reached .
    for example , compute a factorial function would be look like :
def factorial(n):
    if n == 1:
        return 1
    else: 
return n * factorial(n-1)
http://www.python-course.eu/recursive_functions.php [source]

 the program itself is simple. only 5 lines of code .  However, it is really clear that we repetitively call upon the function itself with (n-1) as argument and n*factorial(n-1) as accumulated/final output .

 if n == 1:
        return 1
   this if statement is the base case i called about . with out this piece of code the value of n will keep reduce and function will stuck in to a infinite loop.
 
    from this example, it is quit obvious how recursion work, it essentially breaks down the big and complex problem by finding the similarity (the recursive parts) . and solve the problem in a much efficient way compare with what we have learned in csc108 , write a huge loop with tons of if statement.
 
   overall ,i belive recursion is a powerful tool that will come handy on my later study of computer science

No comments:

Post a Comment