SlideShare uma empresa Scribd logo
1 de 29
Baixar para ler offline
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.
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
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

Mais conteúdo relacionado

Mais procurados

File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Recursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresRecursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresPriyanka Rana
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python TutorialSimplilearn
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 

Mais procurados (20)

File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Recursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresRecursion - Algorithms and Data Structures
Recursion - Algorithms and Data Structures
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Python ppt
Python pptPython ppt
Python ppt
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
List in Python
List in PythonList in Python
List in Python
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Último

Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Amil baba
 
Transforming Process Safety Management: Challenges, Benefits, and Transition ...
Transforming Process Safety Management: Challenges, Benefits, and Transition ...Transforming Process Safety Management: Challenges, Benefits, and Transition ...
Transforming Process Safety Management: Challenges, Benefits, and Transition ...soginsider
 
Gender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 ProjectGender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 Projectreemakb03
 
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfSummer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfNaveenVerma126
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Akarthi keyan
 
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfJulia Kaye
 
Basic Principle of Electrochemical Sensor
Basic Principle of  Electrochemical SensorBasic Principle of  Electrochemical Sensor
Basic Principle of Electrochemical SensorTanvir Moin
 
Design Analysis of Alogorithm 1 ppt 2024.pptx
Design Analysis of Alogorithm 1 ppt 2024.pptxDesign Analysis of Alogorithm 1 ppt 2024.pptx
Design Analysis of Alogorithm 1 ppt 2024.pptxrajesshs31r
 
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Apollo Techno Industries Pvt Ltd
 
Technical Management of cement industry.pdf
Technical Management of cement industry.pdfTechnical Management of cement industry.pdf
Technical Management of cement industry.pdfMadan Karki
 
CSR Managerial Round Questions and answers.pptx
CSR Managerial Round Questions and answers.pptxCSR Managerial Round Questions and answers.pptx
CSR Managerial Round Questions and answers.pptxssusera0771e
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesDIPIKA83
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecTrupti Shiralkar, CISSP
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging systemgokuldongala
 
Mohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptxMohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptxKISHAN KUMAR
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptxSaiGouthamSunkara
 
News web APP using NEWS API for web platform to enhancing user experience
News web APP using NEWS API for web platform to enhancing user experienceNews web APP using NEWS API for web platform to enhancing user experience
News web APP using NEWS API for web platform to enhancing user experienceAkashJha84
 

Último (20)

Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
 
Transforming Process Safety Management: Challenges, Benefits, and Transition ...
Transforming Process Safety Management: Challenges, Benefits, and Transition ...Transforming Process Safety Management: Challenges, Benefits, and Transition ...
Transforming Process Safety Management: Challenges, Benefits, and Transition ...
 
Gender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 ProjectGender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 Project
 
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfSummer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part A
 
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
 
Basic Principle of Electrochemical Sensor
Basic Principle of  Electrochemical SensorBasic Principle of  Electrochemical Sensor
Basic Principle of Electrochemical Sensor
 
Design Analysis of Alogorithm 1 ppt 2024.pptx
Design Analysis of Alogorithm 1 ppt 2024.pptxDesign Analysis of Alogorithm 1 ppt 2024.pptx
Design Analysis of Alogorithm 1 ppt 2024.pptx
 
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
 
Technical Management of cement industry.pdf
Technical Management of cement industry.pdfTechnical Management of cement industry.pdf
Technical Management of cement industry.pdf
 
Lecture 2 .pdf
Lecture 2                           .pdfLecture 2                           .pdf
Lecture 2 .pdf
 
CSR Managerial Round Questions and answers.pptx
CSR Managerial Round Questions and answers.pptxCSR Managerial Round Questions and answers.pptx
CSR Managerial Round Questions and answers.pptx
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display Devices
 
Présentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdfPrésentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdf
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging system
 
Mohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptxMohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptx
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptx
 
News web APP using NEWS API for web platform to enhancing user experience
News web APP using NEWS API for web platform to enhancing user experienceNews web APP using NEWS API for web platform to enhancing user experience
News web APP using NEWS API for web platform to enhancing user experience
 
計劃趕得上變化
計劃趕得上變化計劃趕得上變化
計劃趕得上變化
 

6-Python-Recursion PPT.pptx