Recursive function in python with example
Recurison
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.
Example:
#python program to print factorial of a number using recurion
def factorial(num):
"""
This is a recursive function to find the factorial of a given number
"""
return 1 if num == 1 else (num * factorial(num-1))
num = 15
print ("Factorial of {0} is {1}".format(num, factorial(num)))
Advantages
- 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
- 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.
Python program to display the Fibonacci sequence up to n-th term using recursive function
def fibonacci(num):
"""
Recursive function to print fibonacci sequence
"""
return num if num <= 1 else fibonacci(num-1) + fibonacci(num-2)
nterms = 10
print("Fibonacci sequence")
for num in range(nterms):
print(fibonacci(num))