SlideShare a Scribd company logo
1 of 29
Python: Recursive Functions
Recursive Functions
Recall factorial function:
IterativeAlgorithm
Loop construct (while)
can capture computation in a
set of state variables that
update on each iteration
through loop
Recursive Functions
factorial(n) = n * factorial(n-1)
Alternatively:
Consider
5! = 5x4x3x2x1
can be re-written as 5!=5x4!
In general n! = nx(n-1)!
Recursive Functions
Alternatively:
Consider
5! = 5x4x3x2x1 Recursive Algorithm
can be re-written as 5!=5x4!
function calling itself
In general n! = nx(n-1)!
factorial(n) = n * factorial(n-1)
Recursive Functions
Recursive Functions
Known
Base case
Recursive Functions
Base case
Recursive step
Recursive Functions
Execution trace for n = 4
fact (4)
4 * fact (3)
4 * (3 * fact (2))
4 * (3 * (2 * fact (1)))
4 * (3 * (2 * (1 * fact (0))))
4 * (3 * (2 * (1 * 1)))
4 * (3 * (2 * 1))
4 * (3 * 2)
4 * 6
24
• No computation in first
phase, only function calls
• Deferred/Postponed
computation
– after function calls
terminate, computation
starts
• Sequence of calls have
to be remembered
Courtesy Prof PR Panda CSE Department IIT Dehi
Another Example (Iterative)
Iterative
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Another Example (Recursive)
IterativeAlgorithm
Recursive
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Recursive Functions
• Size of the problem reduces at each step
• The nature of the problem remains the same
• There must be at least one terminating condition
• Simpler, more intuitive
– For inductively defined computation, recursive algorithm
may be natural
• close to mathematical specification
• Easy from programing point of view
• May not efficient computation point of view
GCD Algorithm
gcd (a, b) =
b if a mod b = 0
gcd (b, a mod b) otherwise
Iterative
Algorithm
RecursiveAlgorithm
GCD Algorithm
gcd (a, b) =
b if a mod b = 0
gcd (b, a mod b) otherwise
gcd (6, 10)
gcd (10, 6)
gcd (6, 4)
gcd (4, 2)
2
2
2
2
Courtesy Prof PR Panda CSE Department IIT Dehi
Fibonacci Numbers
fib (n) =
0
1
n = 1
n = 2
fib (n-1) + fib (n-2) n > 2
RecursiveAlgorithm
Courtesy Prof PR Panda CSE Department IIT Dehi
Fibonacci Numbers
fib (6)
fib (5)
fib (4)
fib (3) fib (2)
fib (2) fib (1)
fib (3)
fib (2) fib (1)
fib (4)
fib (3) fib (2)
fib (2) fib (1)
Courtesy Prof PR Panda CSE Department IIT Dehi
Power Function
• Write a function power (x,n) to compute the
nth power of x
power(x,n) =
1 if n = 0
x * power(x,n-1) otherwise
Power Function
• Efficient power function
• Fast Power
– fpower(x,n) = 1 for n = 0
– fpower(x,n) = x * (fpower(x, n/2))2 if n is odd
– fpower(x,n) = (fpower(x, n/2))2 if n is even
Power Function
• Efficient power function
Towers of Hanoi Problem
• 64 gold discs with different
diameters
• Three poles: (Origin, Spare, Final)
• Transfer all discs to final pole
from origin
– one at a time
– spare can be used to temporarily
store discs
– no disk should be placed on a
smaller disk
• Intial Arrangement:
– all on origin pole, largest at bottom,
next above it, etc.
Origin
Courtesy Prof PR Panda CSE Department IIT Dehi
Spare Final
3-Step Strategy
Origin Spare Final Origin Spare Final
Origin Spare Final Origin Spare Final
Solve for (n-1) disks. Move to Spare.
Use Final as Spare.
Move bottom disk to Final
Move (n-1) disks to Final.
Use Origin as Spare.
Courtesy Prof PR Panda CSE Department IIT Dehi
Recursive Solution
Courtesy Prof PR Panda CSE Department IIT Dehi
• Use algorithm for (n-1) disks to solve n-disk problem
• Use algorithm for (n-2) disks to solve (n-1) disk problem
• Use algorithm for (n-3) disks to solve (n-2) disk problem
• ...
• Finally, solve 1-disk problem:
– Just move the disk!
Problem solving with Top Down Design
 Top down design approach, also called as Stepwise refinement, is
essential to develop a well structured program.
 This approach is a problem solving technique that systematically breaks
a complicated problem into smaller, more manageable pieces.
 If any of these subproblems is not easier to solve, we further divide the
subproblem into smaller parts.
 We repeat the subdividing process until all small parts are not dividable.
 Then, we can use a few lines of code to solve every trivial problem. In the
end, we put all these little pieces together as a solution to the original
problem.
 This approach makes it easy to think about the problem, code the
solution read the code and identify bugs.
Steps to solve a problem using Top
Down Design:
1. Start with an initial problem statement.
2. Define subtask at the first level.
3. Divide subtasks at a higher level into
more specific tasks.
4. Repeat step (3) until each subtask is
trivial.
5. Refine the algorithm into real code.
Business requirement Analysis
Initial Problem statement
Read new emails from an email box and save email messages into a database table.
Case study: Gathering Information
from a file system
Import os
os.mkdir(“d:tempdir”)
FILES
Open( )
Syntax
file_object = (“filename.txt”, “Access Mode”)
File pointer
points to the content of file
Access Modes
r – read mode
only for reading the content
file pointer points at the beginning of the file
file should exist before opening in read mode

More Related Content

What's hot (20)

8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Sets in python
Sets in pythonSets in python
Sets in python
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python list
Python listPython list
Python list
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Recursion
RecursionRecursion
Recursion
 
Python functions
Python functionsPython functions
Python functions
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Python Basics
Python BasicsPython Basics
Python Basics
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Python libraries
Python librariesPython libraries
Python libraries
 
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaWhat is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 

Similar to 6-Python-Recursion PPT.pptx

lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptxLizhen Shi
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting classgiridaroori
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103Sure Interview
 
Programming workshop
Programming workshopProgramming workshop
Programming workshopSandeep Joshi
 
RNN sharing at Trend Micro
RNN sharing at Trend MicroRNN sharing at Trend Micro
RNN sharing at Trend MicroChun Hao Wang
 
Neural Network as a function
Neural Network as a functionNeural Network as a function
Neural Network as a functionTaisuke Oe
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
06 Recursion in C.pptx
06 Recursion in C.pptx06 Recursion in C.pptx
06 Recursion in C.pptxMouDhara1
 
Lesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.pptLesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.pptssuser78a386
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 

Similar to 6-Python-Recursion PPT.pptx (20)

6-Python-Recursion.pdf
6-Python-Recursion.pdf6-Python-Recursion.pdf
6-Python-Recursion.pdf
 
Dynamic pgmming
Dynamic pgmmingDynamic pgmming
Dynamic pgmming
 
Recursion
RecursionRecursion
Recursion
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
14 recursion
14 recursion14 recursion
14 recursion
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Dynamicpgmming
DynamicpgmmingDynamicpgmming
Dynamicpgmming
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Programming workshop
Programming workshopProgramming workshop
Programming workshop
 
RNN sharing at Trend Micro
RNN sharing at Trend MicroRNN sharing at Trend Micro
RNN sharing at Trend Micro
 
Mit6 094 iap10_lec03
Mit6 094 iap10_lec03Mit6 094 iap10_lec03
Mit6 094 iap10_lec03
 
FUNDAMETAL ALG.ppt
FUNDAMETAL ALG.pptFUNDAMETAL ALG.ppt
FUNDAMETAL ALG.ppt
 
Neural Network as a function
Neural Network as a functionNeural Network as a function
Neural Network as a function
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
06 Recursion in C.pptx
06 Recursion in C.pptx06 Recursion in C.pptx
06 Recursion in C.pptx
 
WT-Pravesh Sakhare.pptx
WT-Pravesh Sakhare.pptxWT-Pravesh Sakhare.pptx
WT-Pravesh Sakhare.pptx
 
Lesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.pptLesson 4A - Inverses of Functions.ppt
Lesson 4A - Inverses of Functions.ppt
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 

More from Venkateswara Babu Ravipati (12)

EG-Unit-2- Points.pptx
EG-Unit-2- Points.pptxEG-Unit-2- Points.pptx
EG-Unit-2- Points.pptx
 
EG- Unit 1.pptx
EG- Unit 1.pptxEG- Unit 1.pptx
EG- Unit 1.pptx
 
Chapter5.pptx
Chapter5.pptxChapter5.pptx
Chapter5.pptx
 
inputoutput.pptx
inputoutput.pptxinputoutput.pptx
inputoutput.pptx
 
PP ECE A Sec UNIT-1.pptx
PP ECE A Sec UNIT-1.pptxPP ECE A Sec UNIT-1.pptx
PP ECE A Sec UNIT-1.pptx
 
python unit 2.pptx
python unit 2.pptxpython unit 2.pptx
python unit 2.pptx
 
Data types.pdf
Data types.pdfData types.pdf
Data types.pdf
 
types.pdf
types.pdftypes.pdf
types.pdf
 
cad cam and robotics.pptx
cad cam and robotics.pptxcad cam and robotics.pptx
cad cam and robotics.pptx
 
unit3.pptx
unit3.pptxunit3.pptx
unit3.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Le and ne algorithms
Le and ne algorithmsLe and ne algorithms
Le and ne algorithms
 

Recently uploaded

Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...vershagrag
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfsumitt6_25730773
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...gragchanchal546
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 

Recently uploaded (20)

Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 

6-Python-Recursion PPT.pptx