SlideShare a Scribd company logo
PYTHON RECURSION
PYTHON RECURSION
What is recursion?
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.
PYTHON RECURSIVE
FUNCTION
In Python, we know that a function can call
other functions.
It is even possible for the function to call
itself.
These types of construct are termed as
recursive functions.
The following image shows the working of a
recursive function called recurse.
EXAMPLE OF A RECURSIVE
FUNCTION
Following is an example of a 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 factorial(x):
"""This is a recursive function to find the factorial
of
an integer""“
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output: The factorial of 3 is 6
• When we call this function with a positive integer,
it will recursively call itself by decreasing the number.
• Each function multiplies the number with the factorial of the number below it
until it is equal to one. This recursive call can be explained in the following steps.
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3 * 2 * 1 # return from 3rd call as number=1
3 * 2 # return from 2nd call 6 # return from 1st call
Let's look at an image that
shows a step-by-step process
of what is going on:
• Our recursion ends when the number reduces to 1. This is called the base condition.
• Every recursive function must have a base condition that stops the recursion or else
the function calls itself infinitely.
• The Python interpreter limits the depths of recursion to help avoid infinite recursions,
resulting in stack overflows.
• By default, the maximum depth of recursion is 1000.
• If the limit is crossed, it results in RecursionError.
Let's look at one such condition.
def recursor():
recursor()
recursor()
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Example 1: A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3,
5, 8….
# Program to print the fibonacci series upto n_terms
# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
Output
Fibonacci
series:
0
1
1
2
3
5
8
13
21
34
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
1.Sometimes the logic behind recursion is hard to follow through.
2.Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
3.Recursive functions are hard to debug.

More Related Content

Similar to DSA. Data structure algorithm dRecursion.pptx (20)

PDF
Recursion in Python.pdf
MayankSinghRawat6
 
PDF
Python Programming unit5 (1).pdf
jamvantsolanki
 
PPTX
Enhanced_Recursion_Presennnnntation.pptx
AliAbbas574107
 
PPTX
Recursive Algorithms with their types and implementation
Ahmad177077
 
PPTX
Python recursion
ToniyaP1
 
PPTX
It is a way of programming or coding technique, in which a function calls it...
ssuser5ecd1a
 
PDF
6-Python-Recursion.pdf
AshishPalandurkar2
 
PPTX
Recursion
Esther Leytush
 
PDF
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
arijitghosal14
 
PPTX
Recursion part 2
Keerty Smile
 
PDF
Chapter 7 recursion handouts with notes
mailund
 
PDF
Effective Algorithm for n Fibonacci Number By: Professor Lili Saghafi
Professor Lili Saghafi
 
PDF
14. Recursion.pdf
VivekBhimajiyani
 
PPTX
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
PPT
Recursion C programming exercises_ Recursion - w3resource.ppt
Carlos701746
 
DOCX
Recursion in C++
Maliha Mehr
 
PDF
Recursive Algorithms coded in Python.pdf
drthpeters
 
PDF
Recursion For the Rest of Us (CS Fundamentals Series)
Haseeb Qureshi
 
PPT
Lec-6 Recursion of Data Structures & Algorithms
haseebanjum2611
 
PPTX
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 
Recursion in Python.pdf
MayankSinghRawat6
 
Python Programming unit5 (1).pdf
jamvantsolanki
 
Enhanced_Recursion_Presennnnntation.pptx
AliAbbas574107
 
Recursive Algorithms with their types and implementation
Ahmad177077
 
Python recursion
ToniyaP1
 
It is a way of programming or coding technique, in which a function calls it...
ssuser5ecd1a
 
6-Python-Recursion.pdf
AshishPalandurkar2
 
Recursion
Esther Leytush
 
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
arijitghosal14
 
Recursion part 2
Keerty Smile
 
Chapter 7 recursion handouts with notes
mailund
 
Effective Algorithm for n Fibonacci Number By: Professor Lili Saghafi
Professor Lili Saghafi
 
14. Recursion.pdf
VivekBhimajiyani
 
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
Recursion C programming exercises_ Recursion - w3resource.ppt
Carlos701746
 
Recursion in C++
Maliha Mehr
 
Recursive Algorithms coded in Python.pdf
drthpeters
 
Recursion For the Rest of Us (CS Fundamentals Series)
Haseeb Qureshi
 
Lec-6 Recursion of Data Structures & Algorithms
haseebanjum2611
 
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 

Recently uploaded (20)

PPTX
TSM_08_0811111111111111111111111111111111111111111111111
csomonasteriomoscow
 
PPTX
GenAI-Introduction-to-Copilot-for-Bing-March-2025-FOR-HUB.pptx
cleydsonborges1
 
PDF
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
DOC
MATRIX_AMAN IRAWAN_20227479046.docbbbnnb
vanitafiani1
 
DOCX
AI/ML Applications in Financial domain projects
Rituparna De
 
PPTX
fashion industry boom.pptx an economics project
TGMPandeyji
 
PDF
Building Production-Ready AI Agents with LangGraph.pdf
Tamanna
 
PPTX
AI Project Cycle and Ethical Frameworks.pptx
RiddhimaVarshney1
 
PPTX
Exploring Multilingual Embeddings for Italian Semantic Search: A Pretrained a...
Sease
 
PPTX
Slide studies GC- CRC - PC - HNC baru.pptx
LLen8
 
PDF
How to Avoid 7 Costly Mainframe Migration Mistakes
JP Infra Pvt Ltd
 
PPTX
Advanced_NLP_with_Transformers_PPT_final 50.pptx
Shiwani Gupta
 
PPT
Data base management system Transactions.ppt
gandhamcharan2006
 
PPTX
Resmed Rady Landis May 4th - analytics.pptx
Adrian Limanto
 
PPT
Lecture 2-1.ppt at a higher learning institution such as the university of Za...
rachealhantukumane52
 
PDF
How to Connect Your On-Premises Site to AWS Using Site-to-Site VPN.pdf
Tamanna
 
PDF
Context Engineering vs. Prompt Engineering, A Comprehensive Guide.pdf
Tamanna
 
PDF
T2_01 Apuntes La Materia.pdfxxxxxxxxxxxxxxxxxxxxxxxxxxxxxskksk
mathiasdasilvabarcia
 
PPTX
Rocket-Launched-PowerPoint-Template.pptx
Arden31
 
PPTX
apidays Munich 2025 - Building Telco-Aware Apps with Open Gateway APIs, Subhr...
apidays
 
TSM_08_0811111111111111111111111111111111111111111111111
csomonasteriomoscow
 
GenAI-Introduction-to-Copilot-for-Bing-March-2025-FOR-HUB.pptx
cleydsonborges1
 
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
MATRIX_AMAN IRAWAN_20227479046.docbbbnnb
vanitafiani1
 
AI/ML Applications in Financial domain projects
Rituparna De
 
fashion industry boom.pptx an economics project
TGMPandeyji
 
Building Production-Ready AI Agents with LangGraph.pdf
Tamanna
 
AI Project Cycle and Ethical Frameworks.pptx
RiddhimaVarshney1
 
Exploring Multilingual Embeddings for Italian Semantic Search: A Pretrained a...
Sease
 
Slide studies GC- CRC - PC - HNC baru.pptx
LLen8
 
How to Avoid 7 Costly Mainframe Migration Mistakes
JP Infra Pvt Ltd
 
Advanced_NLP_with_Transformers_PPT_final 50.pptx
Shiwani Gupta
 
Data base management system Transactions.ppt
gandhamcharan2006
 
Resmed Rady Landis May 4th - analytics.pptx
Adrian Limanto
 
Lecture 2-1.ppt at a higher learning institution such as the university of Za...
rachealhantukumane52
 
How to Connect Your On-Premises Site to AWS Using Site-to-Site VPN.pdf
Tamanna
 
Context Engineering vs. Prompt Engineering, A Comprehensive Guide.pdf
Tamanna
 
T2_01 Apuntes La Materia.pdfxxxxxxxxxxxxxxxxxxxxxxxxxxxxxskksk
mathiasdasilvabarcia
 
Rocket-Launched-PowerPoint-Template.pptx
Arden31
 
apidays Munich 2025 - Building Telco-Aware Apps with Open Gateway APIs, Subhr...
apidays
 
Ad

DSA. Data structure algorithm dRecursion.pptx

  • 2. PYTHON RECURSION What is recursion? 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.
  • 3. PYTHON RECURSIVE FUNCTION In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions. The following image shows the working of a recursive function called recurse.
  • 4. EXAMPLE OF A RECURSIVE FUNCTION Following is an example of a 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 factorial(x): """This is a recursive function to find the factorial of an integer""“ if x == 1: return 1 else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num)) Output: The factorial of 3 is 6
  • 5. • When we call this function with a positive integer, it will recursively call itself by decreasing the number. • Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps. factorial(3) # 1st call with 3 3 * factorial(2) # 2nd call with 2 3 * 2 * factorial(1) # 3rd call with 1 3 * 2 * 1 # return from 3rd call as number=1 3 * 2 # return from 2nd call 6 # return from 1st call
  • 6. Let's look at an image that shows a step-by-step process of what is going on:
  • 7. • Our recursion ends when the number reduces to 1. This is called the base condition. • Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely. • The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack overflows. • By default, the maximum depth of recursion is 1000. • If the limit is crossed, it results in RecursionError. Let's look at one such condition. def recursor(): recursor() recursor() Output Traceback (most recent call last): File "<string>", line 3, in <module> File "<string>", line 2, in a File "<string>", line 2, in a File "<string>", line 2, in a [Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded
  • 8. Example 1: A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8…. # Program to print the fibonacci series upto n_terms # Recursive function def recursive_fibonacci(n): if n <= 1: return n else: return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2)) n_terms = 10 # check if the number of terms is valid if n_terms <= 0: print("Invalid input ! Please input a positive value") else: print("Fibonacci series:") for i in range(n_terms): print(recursive_fibonacci(i)) Output Fibonacci series: 0 1 1 2 3 5 8 13 21 34
  • 9. 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.
  • 10. DISADVANTAGES OF RECURSION 1.Sometimes the logic behind recursion is hard to follow through. 2.Recursive calls are expensive (inefficient) as they take up a lot of memory and time. 3.Recursive functions are hard to debug.