Python Recursion

What are recursive functions?

Until now we had been defining a feature and on the time of execution, we had been calling it from out of doors the feature. What if we name the feature in the feature? it's going to create a kinda loop that what recursion capabilities are all about.

A recursive feature is that feature that can name itself all through execution. For example, whilst a feature frame has a declaration wherein it's miles calling itself then that feature can be termed as a recursive feature.

We have stated that recursion act like loops what can carry out repetitive paintings so there need to be a base situation that prevents that repetitive declaration and provide a end result otherwise you may get entice within side the limitless loop.

Go this blog on bubble sort program in c using function to know how the function works with examples.

Python recursive Function

Let’s code

def fact(n):
    if n==1 or n==0:                           #Base condition
        return 1
    else:
        return n * fact(n-1)                    # recursion function calling

num=7
print("the factorial of" ,num, "is ", fact(num))                     #function calling

Output

the factorial of 7 is 5040

Work behind the code:

In the above example to execute the function fact(), we call it from outside the function then the value of variable num gets assigned to the function argument n and function gets started to execute when the argument n does not satisfy the if statement the else statement gets executed. In the else statement we strike the recursive function and let’s see how does it work.

fact(n)                  #main function
    return 7 * fact(6)                #recursive function first call
        return  7 * 6 *fact(5)            #recursive function 2nd call (the value of fact(6) is 6 * fact(5))
            return 7*6*5*fact(4)              #recursive function 3rd call
                return  7*6*5*4 *fact(3)           #recursive function 4th call
                    return 7*6*5*4*3*fact(2)            #recursive function 5th call
                        return 7*6*5*4*3*2*fact(1)          #recursive function 6th call
                            return 7*6*5*4*3*2*1                  #recursive function 7th call

Pro and Cons of recursive function:

Advantages:

  • With recursion characteristic, the code appears neat
  • It divides the capability into smaller components which make the programme clean to apprehend
  • It comes very usefully with the binary timber records structure

Disadvantages:

  • It’s very tough to apprehend the good judgment in the back of each recursive characteristic.
  • A recursive characteristic is gradual as evaluate to the iterators.
  • It occupies a variety of reminiscence due to the fact we're executing the identical characteristic once more and once more
  • It's far very difficult to debug the recursive characteristic. With a huge set of records, recursive capabilities aren't useful

18