Thursday, 3 March 2016

Recursion : Week 7

Recursion is a new topic which has been covered this week. In the starting it was hard to understand as it is a bit complicated. From what I understand, Recursion is a way of coding, in which a function calls itself one or more times in its body. Basically, it returns the return value of this function call. 
If a function definition fulfils the condition of recursion, we call this function a Recursive function. 

Termination : The termination of these functions occur if with every recursive call the return value of the problem is downsized and moves towards its base case. A base case is a case where no further recursion is required or occurs. 

Note : If there is no base case, recursion can lead to an infinite loop. 

Example, the way in which the factorial recursive function works : 
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1! (the recursive function breaks here as n becomes 1)

Replacing the calculated values gives us the following expression : 
4! = 4 * 3 * 2 * 1 

def fact(n):
   """This is a recursive function to find the factorial of an integer, n
   ””"
   if n == 1:
       return 1
   else:
       return (n * fact(n-1))

The above is the code of a sample recursive function(factorial), here the base case is at n = 1 where the function returns the value 1.

Advantages of recursion : 
  1. Usage of recursive functions make the code look clean and elegant.
  2. Using recursion, a complex task can be broken down into simpler sub-problems.

Disadvantages of recursion : 
  1. Sometimes the logic behind recursion is hard to follow.
  2. Recursive calls take up a lot of memory and time.




No comments:

Post a Comment