Wednesday, August 16, 2017

Python Recursive Function

Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition fulfils the condition of recursion, we call this function a recursive function. 

Termination condition:
A recursive function has to terminate to be used in a program. A recursive function terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case. A base case is a case, where the problem can be solved without further recursion. A recursion can lead to an infinite loop, if the base case is not met in the calls. 

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

Generally we can say: Recursion in computer science is a method where the solution to a problem is based on solving smaller instances of the same problem. 
#Recursive function to calculate the cumulative sum of a list
def cum_sum(l=None):
    if len(l) <= 1: return l[0]
    else: return l[0]+cum_sum(l[1:len(l)])

#Recursive function to calculate the the factorial of a number
def fact(number):
    if number == 1: return 1
    else: return number * fact(number-1)
    
print(cum_sum([1,2,3,4,5,6,7,8,9]))
print(fact(3))

#45
#6

1 comment:

  1. To increase the default recursion depth use
    import sys
    sys.setrecursionlimit(n)

    ReplyDelete