Definition, Example, Advantages, Disadvantage - Recursion - Python | Problem Solving and Python Programming : Control Flow, Functions

Chapter: Problem Solving and Python Programming : Control Flow, Functions

Recursion - Python

Recursion is the process of calling the function that is currently executing.

Recursion

 

Recursion is the process of calling the function that is currently executing. It is legal for one function to call another; it is also legal for a function to call itself. 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.

#An example of a recursive function to

#find the factorial of a number

def calc_factorial(x):

"""This is a recursive function to find the factorial of an integer"""

if x == 1:

return 1

else:

return (x * calc_factorial(x-1))

num = 4

print("The factorial of", num, "is", calc_factorial(num))

 

Output:

The factorial of 4 is 24

 

The 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.


The 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.

 

Tags : Definition, Example, Advantages, Disadvantage , Problem Solving and Python Programming : Control Flow, Functions
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Control Flow, Functions : Recursion - Python | Definition, Example, Advantages, Disadvantage


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.