SlideShare a Scribd company logo
1 of 20
Recursion
Saverio Perugini, Ph.D.
Ave Maria University
Pro Deo et Patria.
Sancte Ioseph, Exémplar opı́ficum, Ora pro nobis.
Sancte Thoma de Aquino, Patronus academicorum, Ora pro nobis.
Sancte Patricius, Ora pro nobis.
January 18, 2024
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 1 / 20
Overview
Recursion: What?, Why?, and How?
Recursion over Numbers
Recursion over Lists
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 2 / 20
What is Recursion?
Solving a problem by defining a function in terms of itself.
(necessary, but not sufficient)
To be recursive, a function must not only call itself, but must do so in a
way such that each successive recursive call reduces the problem to a
smaller instance of the problem until the problem can get no smaller (i.e.,
when the base case is reached).
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 3 / 20
Why Recursion?
Recursion provides a clean and simple way to write code.
Some algorithms are inherently recursive (e.g., mergesort).
Using recursion, certain problems can be solved quite easily and
elegantly.
Examples: tree traversals (preorder, inorder, postorder),
graph algorithms (e.g., depth-first search)
The ability to think recursively is a staple in the design toolkit of
computer scientists (and mathematicians).
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 4 / 20
Preliminaries (from Discrete Mathematics)
What is a set?
A set is a collection of items without duplicates.
Examples: N, Z, colors, states, and Saints.
What is a function?
A function is a mapping from a domain to a range, where the domain
and range are sets.
Examples: f (x) = x + 1 is a function f : Z → Z
(truncate) t : R → Z
1
1
Figure from VanDrunen, T. (2013). Discrete Mathematics and Functional Programming. Portland, OR: Franklin Beedle
& Associates Inc.
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 5 / 20
How to Design a Recursive Function
Step 1: Determine (and solve) the Base Case
The base case is the smallest instance of the problem.
Example: Factorial function f (n) = n!
The base case is n = 0 and f (0) = 0! = 1.
Step 2: Extend the Solution to Penultimate Case to the Solution to
the Ultimate Case
a. Assume the penultimate [(n−1)th] instance of the problem is solved.
b. Demonstrate how to extend that (n−1) solution to the solution to the
nth instance of the problem.
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 6 / 20
Do Not Try to Solve the Penultimate Case
Show how to extend
Assume this is solved!
z }| {
f (n−1) =⇒
|{z}
This is the extension we need to figure out.
We want to solve:
z}|{
f (n)
For a recursive factorial function (assume n = 5):
Assume this is solved!
z }| {
f (n−1) = f (4) = 24 =⇒
|{z}
multiply by n
This is what we want to solve.
z }| {
f (n) = f (5) = 120
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 7 / 20
In Python programming, these steps look like:
Step 1: Determine (and solve) the Base Case
# Base Case: n=0, 0! = 1
def factorial(n) =
if n == 0:
return 1
Step 2: Extend the Solution of Penultimate Case to the Solution to
the Ultimate Case
# Base Case: n=0, 0! = 1
def factorial(n) =
if n == 0:
return 1
else:
# Assume n-1 case is solved. Now extend.
return factorial(n-1) * n;
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 8 / 20
The Expansion of factorial(5)
Example
factorial(5)
5 * factorial(4)
5 * (4 * factorial(3))
5 * (4 * (3 * factorial(2)))
5 * (4 * (3 * (2 * factorial(1))))
5 * (4 * (3 * (2 * (1 * factorial(0))))) # base case
5 * (4 * (3 * (2 * (1 * 1))))
5 * (4 * (3 * (2 * 1)))
5 * (4 * (3 * 2))
5 * (4 * 6)
5 * 24
120
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 9 / 20
Points to Consider
Some problems have more than one base case.
Similarly, in some problems we must consider the penultimate case
and some cases before the penultimate case.
Consider the Fibonacci numbers.
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 10 / 20
The Fibonacci Numbers
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, . . . , 6765, 10946, 17711, . . .
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 11 / 20
The Fibonacci Numbers: The Golden Mean
0, 1, 1, 2,
5
3
=1.666
z}|{
3, 5 , 8, 13
|{z}
13
8
=1.625
, 21, 34, 55, . . . ,
10946
6765
=1.618
z }| {
6765, 10946, 17711, . . .
Referred to as the Golden ratio or Golden mean (1.618)
Repeatedly occurs in nature, describes a form of a spiral
Humans tend to find the golden mean aesthetically pleasing.
Architects design windows, rooms, and buildings with a golden mean
length/width ratio.
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 12 / 20
The Fibonacci Numbers
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, . . . , 6765, 10946, 17711, . . .
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 13 / 20
The Fibonacci Numbers
0, 1, 1, 2,
3+5=8
z }| {
3, 5, 8, 13, 21, 34, 55
| {z }
21+34=55
, . . . ,
6765+10946=17711
z }| {
6765, 10946, 17711, . . .
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 14 / 20
The Fibonacci Numbers (continued)
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, . . . , 6765, 10946, 17711, . . .
Mathematical Definition:
F0 = 0
F1 = 1
Fn = Fn−1 + Fn−2
Functionally, fibonacci : W → W
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n−1) + fibonacci(n−2)
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 15 / 20
How Can We Define a List Recursively?
Follow the same process/steps for defining a function recursively.
A list is either empty or has a head and a tail, where the head is an
element and the tail is a list.
values/contents
0 2
head
3 17 22
tail
1 indices
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 16 / 20
A Theme
Algorithms ←→ Data Structures
Thus, “when defining a program based on structural induction, the
structure of the program should be patterned after the structure of the
data.”2
We proceed with this theme in mind.
2
Friedman, D.P., and M. Wand. 2008. Essentials of Programming Languages. Third. Cambridge, MA: MIT Press.
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 17 / 20
Some Helpful Python List Idioms
Python Semantics
[] the empty list
L[0] the head of list L
e.g., if L = [3,17,22], then L[0] returns 3
L[1:] the tail of list L
e.g., if L = [3,17,22], then L[1:] returns [17,22]
len(L) returns the length (i.e., size) of list L
e.g., if L = [3,17,22], then len(L) returns 3
L1 + L2 appends lists L1 and L2
e.g., if L1 = [3,17,22] and L2 = [3,18,22], then
L1 + L2 returns [3,17,22,3,18,22]
e in L returns True if element e is in list L and False otherwise
e.g., 17 in [3,17,22] returns True and
18 in [3,17,22] returns False
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 18 / 20
Examples of Recursion Over Lists
member
remove
makeset
append
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 19 / 20
Review and Reflection
Process and Patterns
Recursion over numbers
factorial
fibonacci
square
Recursion over lists
member
remove
makeset
append
Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 20 / 20

More Related Content

Similar to Recursion (in Python)

Finding the Extreme Values with some Application of Derivatives
Finding the Extreme Values with some Application of DerivativesFinding the Extreme Values with some Application of Derivatives
Finding the Extreme Values with some Application of Derivativesijtsrd
 
Transfer Learning for the Detection and Classification of traditional pneumon...
Transfer Learning for the Detection and Classification of traditional pneumon...Transfer Learning for the Detection and Classification of traditional pneumon...
Transfer Learning for the Detection and Classification of traditional pneumon...Yusuf Brima
 
352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-doc352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-docBookStoreLib
 
352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-doc352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-docFiras Husseini
 
Demo_Teaching_Mathematics_Powerpoint.pptx
Demo_Teaching_Mathematics_Powerpoint.pptxDemo_Teaching_Mathematics_Powerpoint.pptx
Demo_Teaching_Mathematics_Powerpoint.pptxdanilofrondajr27
 
Introduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions ManualIntroduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions ManualDawsonVeronica
 
Problem solving content
Problem solving contentProblem solving content
Problem solving contentTimothy Welsh
 
problem_solving in physics
 problem_solving in physics problem_solving in physics
problem_solving in physicsTimothy Welsh
 
Bridging knowing and proving in mathematics
Bridging knowing and proving in mathematicsBridging knowing and proving in mathematics
Bridging knowing and proving in mathematicsNicolas Balacheff
 
SESSION-12 PPT.pptx
SESSION-12 PPT.pptxSESSION-12 PPT.pptx
SESSION-12 PPT.pptxNaniSarath
 
Predicate calculus
Predicate calculusPredicate calculus
Predicate calculusRajendran
 
Quantitative Analysis For Management 11th Edition Render Test Bank
Quantitative Analysis For Management 11th Edition Render Test BankQuantitative Analysis For Management 11th Edition Render Test Bank
Quantitative Analysis For Management 11th Edition Render Test BankRichmondere
 
Why recursion is impotant_new_my.docx
Why recursion is impotant_new_my.docxWhy recursion is impotant_new_my.docx
Why recursion is impotant_new_my.docxMiracule D Gavor
 
Power Full Exposition
Power Full ExpositionPower Full Exposition
Power Full ExpositionHeesu Hwang
 

Similar to Recursion (in Python) (20)

chap2.pdf
chap2.pdfchap2.pdf
chap2.pdf
 
QMC: Transition Workshop - Selected Highlights from the Probabilistic Numeric...
QMC: Transition Workshop - Selected Highlights from the Probabilistic Numeric...QMC: Transition Workshop - Selected Highlights from the Probabilistic Numeric...
QMC: Transition Workshop - Selected Highlights from the Probabilistic Numeric...
 
Finding the Extreme Values with some Application of Derivatives
Finding the Extreme Values with some Application of DerivativesFinding the Extreme Values with some Application of Derivatives
Finding the Extreme Values with some Application of Derivatives
 
Transfer Learning for the Detection and Classification of traditional pneumon...
Transfer Learning for the Detection and Classification of traditional pneumon...Transfer Learning for the Detection and Classification of traditional pneumon...
Transfer Learning for the Detection and Classification of traditional pneumon...
 
352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-doc352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-doc
 
352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-doc352735322 rsh-qam11-tif-02-doc
352735322 rsh-qam11-tif-02-doc
 
project
projectproject
project
 
Demo_Teaching_Mathematics_Powerpoint.pptx
Demo_Teaching_Mathematics_Powerpoint.pptxDemo_Teaching_Mathematics_Powerpoint.pptx
Demo_Teaching_Mathematics_Powerpoint.pptx
 
Introduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions ManualIntroduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions Manual
 
Problem solving content
Problem solving contentProblem solving content
Problem solving content
 
problem_solving in physics
 problem_solving in physics problem_solving in physics
problem_solving in physics
 
Bridging knowing and proving in mathematics
Bridging knowing and proving in mathematicsBridging knowing and proving in mathematics
Bridging knowing and proving in mathematics
 
PERT
PERTPERT
PERT
 
SESSION-12 PPT.pptx
SESSION-12 PPT.pptxSESSION-12 PPT.pptx
SESSION-12 PPT.pptx
 
Predicate calculus
Predicate calculusPredicate calculus
Predicate calculus
 
artficial intelligence
artficial intelligenceartficial intelligence
artficial intelligence
 
Quantitative Analysis For Management 11th Edition Render Test Bank
Quantitative Analysis For Management 11th Edition Render Test BankQuantitative Analysis For Management 11th Edition Render Test Bank
Quantitative Analysis For Management 11th Edition Render Test Bank
 
report
reportreport
report
 
Why recursion is impotant_new_my.docx
Why recursion is impotant_new_my.docxWhy recursion is impotant_new_my.docx
Why recursion is impotant_new_my.docx
 
Power Full Exposition
Power Full ExpositionPower Full Exposition
Power Full Exposition
 

Recently uploaded

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 

Recently uploaded (20)

Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 

Recursion (in Python)

  • 1. Recursion Saverio Perugini, Ph.D. Ave Maria University Pro Deo et Patria. Sancte Ioseph, Exémplar opı́ficum, Ora pro nobis. Sancte Thoma de Aquino, Patronus academicorum, Ora pro nobis. Sancte Patricius, Ora pro nobis. January 18, 2024 Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 1 / 20
  • 2. Overview Recursion: What?, Why?, and How? Recursion over Numbers Recursion over Lists Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 2 / 20
  • 3. What is Recursion? Solving a problem by defining a function in terms of itself. (necessary, but not sufficient) To be recursive, a function must not only call itself, but must do so in a way such that each successive recursive call reduces the problem to a smaller instance of the problem until the problem can get no smaller (i.e., when the base case is reached). Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 3 / 20
  • 4. Why Recursion? Recursion provides a clean and simple way to write code. Some algorithms are inherently recursive (e.g., mergesort). Using recursion, certain problems can be solved quite easily and elegantly. Examples: tree traversals (preorder, inorder, postorder), graph algorithms (e.g., depth-first search) The ability to think recursively is a staple in the design toolkit of computer scientists (and mathematicians). Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 4 / 20
  • 5. Preliminaries (from Discrete Mathematics) What is a set? A set is a collection of items without duplicates. Examples: N, Z, colors, states, and Saints. What is a function? A function is a mapping from a domain to a range, where the domain and range are sets. Examples: f (x) = x + 1 is a function f : Z → Z (truncate) t : R → Z 1 1 Figure from VanDrunen, T. (2013). Discrete Mathematics and Functional Programming. Portland, OR: Franklin Beedle & Associates Inc. Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 5 / 20
  • 6. How to Design a Recursive Function Step 1: Determine (and solve) the Base Case The base case is the smallest instance of the problem. Example: Factorial function f (n) = n! The base case is n = 0 and f (0) = 0! = 1. Step 2: Extend the Solution to Penultimate Case to the Solution to the Ultimate Case a. Assume the penultimate [(n−1)th] instance of the problem is solved. b. Demonstrate how to extend that (n−1) solution to the solution to the nth instance of the problem. Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 6 / 20
  • 7. Do Not Try to Solve the Penultimate Case Show how to extend Assume this is solved! z }| { f (n−1) =⇒ |{z} This is the extension we need to figure out. We want to solve: z}|{ f (n) For a recursive factorial function (assume n = 5): Assume this is solved! z }| { f (n−1) = f (4) = 24 =⇒ |{z} multiply by n This is what we want to solve. z }| { f (n) = f (5) = 120 Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 7 / 20
  • 8. In Python programming, these steps look like: Step 1: Determine (and solve) the Base Case # Base Case: n=0, 0! = 1 def factorial(n) = if n == 0: return 1 Step 2: Extend the Solution of Penultimate Case to the Solution to the Ultimate Case # Base Case: n=0, 0! = 1 def factorial(n) = if n == 0: return 1 else: # Assume n-1 case is solved. Now extend. return factorial(n-1) * n; Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 8 / 20
  • 9. The Expansion of factorial(5) Example factorial(5) 5 * factorial(4) 5 * (4 * factorial(3)) 5 * (4 * (3 * factorial(2))) 5 * (4 * (3 * (2 * factorial(1)))) 5 * (4 * (3 * (2 * (1 * factorial(0))))) # base case 5 * (4 * (3 * (2 * (1 * 1)))) 5 * (4 * (3 * (2 * 1))) 5 * (4 * (3 * 2)) 5 * (4 * 6) 5 * 24 120 Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 9 / 20
  • 10. Points to Consider Some problems have more than one base case. Similarly, in some problems we must consider the penultimate case and some cases before the penultimate case. Consider the Fibonacci numbers. Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 10 / 20
  • 11. The Fibonacci Numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, . . . , 6765, 10946, 17711, . . . Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 11 / 20
  • 12. The Fibonacci Numbers: The Golden Mean 0, 1, 1, 2, 5 3 =1.666 z}|{ 3, 5 , 8, 13 |{z} 13 8 =1.625 , 21, 34, 55, . . . , 10946 6765 =1.618 z }| { 6765, 10946, 17711, . . . Referred to as the Golden ratio or Golden mean (1.618) Repeatedly occurs in nature, describes a form of a spiral Humans tend to find the golden mean aesthetically pleasing. Architects design windows, rooms, and buildings with a golden mean length/width ratio. Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 12 / 20
  • 13. The Fibonacci Numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, . . . , 6765, 10946, 17711, . . . Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 13 / 20
  • 14. The Fibonacci Numbers 0, 1, 1, 2, 3+5=8 z }| { 3, 5, 8, 13, 21, 34, 55 | {z } 21+34=55 , . . . , 6765+10946=17711 z }| { 6765, 10946, 17711, . . . Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 14 / 20
  • 15. The Fibonacci Numbers (continued) 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, . . . , 6765, 10946, 17711, . . . Mathematical Definition: F0 = 0 F1 = 1 Fn = Fn−1 + Fn−2 Functionally, fibonacci : W → W fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n−1) + fibonacci(n−2) Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 15 / 20
  • 16. How Can We Define a List Recursively? Follow the same process/steps for defining a function recursively. A list is either empty or has a head and a tail, where the head is an element and the tail is a list. values/contents 0 2 head 3 17 22 tail 1 indices Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 16 / 20
  • 17. A Theme Algorithms ←→ Data Structures Thus, “when defining a program based on structural induction, the structure of the program should be patterned after the structure of the data.”2 We proceed with this theme in mind. 2 Friedman, D.P., and M. Wand. 2008. Essentials of Programming Languages. Third. Cambridge, MA: MIT Press. Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 17 / 20
  • 18. Some Helpful Python List Idioms Python Semantics [] the empty list L[0] the head of list L e.g., if L = [3,17,22], then L[0] returns 3 L[1:] the tail of list L e.g., if L = [3,17,22], then L[1:] returns [17,22] len(L) returns the length (i.e., size) of list L e.g., if L = [3,17,22], then len(L) returns 3 L1 + L2 appends lists L1 and L2 e.g., if L1 = [3,17,22] and L2 = [3,18,22], then L1 + L2 returns [3,17,22,3,18,22] e in L returns True if element e is in list L and False otherwise e.g., 17 in [3,17,22] returns True and 18 in [3,17,22] returns False Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 18 / 20
  • 19. Examples of Recursion Over Lists member remove makeset append Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 19 / 20
  • 20. Review and Reflection Process and Patterns Recursion over numbers factorial fibonacci square Recursion over lists member remove makeset append Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 20 / 20