KEMBAR78
Recursion (in Python) | PDF
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

Recursion (in Python)

  • 1.
    Recursion Saverio Perugini, Ph.D. AveMaria 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? Solvinga 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 providesa 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 DiscreteMathematics) 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 Designa 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 Tryto 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 offactorial(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 Someproblems 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 WeDefine 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 PythonList 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 RecursionOver Lists member remove makeset append Saverio Perugini, Ph.D. (AMU) Recursion January 18, 2024 19 / 20
  • 20.
    Review and Reflection Processand 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