Wednesday, 5 April 2017

Python Recursive Function

Python Recursive Function:


  • Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
  • We know that in Python, a function can call other functions. It is even possible for the function to call itself. These type of construct are termed as recursive functions.
  • Following is an example of recursive function to find the factorial of an integer. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.


def recur_fact(x):
   """This is a recursive function
   to find the factorial of an integer"""

   if x == 1:
       return 1
   else:
       return (x * recur_fact(x-1))


num = int(input("Enter a number: "))
if num >= 1:
   print("The factorial of", num, "is", recur_fact(num))

Enter a number: 6
The factorial of 6 is 720

Advantages of recursion
  •  Recursive functions make the code look clean and elegant.
  •  A complex task can be broken down into simpler sub-problems using recursion.
  • Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of recursion
  • Sometimes the logic behind recursion is hard to follow through.
  • Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
  • Recursive functions are hard to debug.

Recursion vs Iteration

i) In recursion, function call itself until the base condition is reached.
On other hand iteration means repetition of process until the condition fails. For example –  when you use loop (for,while etc.) in your programs.
ii) Iterative approach involves four steps, initialization , condition, execution and  updation.
In recursive function, only base condition (terminate condition) is specified.
iii) Recursion keeps your code short and simple Whereas iterative approach makes your code longer.
iv) Recursion is slower than iteration due to overhead of maintaining stack whereas iteration is faster.
v) Recursion takes more memory than iteration due to overhead of maintaining stack  .



No comments:

Post a Comment