Programming with Python
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Module 12: Recursion
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Module Objectives (1 of 2)
• 12.1 Key Components of Recursion
• 12.1.1 Define recursion as a problem-solving approach.
• 12.1.2 Describe the purpose of recursion.
• 12.1.3 Explain the components of a recursive function.
• 12.1.4 List advantages and disadvantages of recursion.
• 12.2 Using Recursion To Solve Complex Problems
• 12.2.1 Explain the application of recursion.
• 12.2.2 Differentiate recursive algorithms from algorithms that use repetition control
structures.
• 12.2.3 Define the “divide and conquer” approach to problem solving.
• 12.2.4 Analyze how to use a base case and a recursive case to implement recursion into
an iterative programming solution.
• 12.2.5 Construct a procedural program using recursion.
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Module Objectives (2 of 2)
• 12.3 Managing Memory During Recursion
• 12.3.1 Explain memory management and its importance with recursion.
• 12.3.2 Explain the use of a stack during recursion.
• 12.3.3 Explain tail-recursive functions.
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.1 Key Components of Recursion (1 of 7)
• The recursive mindset
• Recursion is the problem-solving approach that divides large problems into smaller,
identical problems
• The same steps are applied to each smaller version of the problem, although with
different restrictions
• Recursion basics
• Recursion solves problems using functions, which:
• Are named blocks of code that perform a specific task
• Can have information passed to them as parameters
• Can return information as return values, which can be used for calculations and
other operations
• Can be called to execute the lines of code inside the function
• Can call other functions
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.1 Key Components of Recursion (2 of 7)
Figure 12-3 Guessing game using
function calls
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.1 Key Components of Recursion (3 of 7)
• Recursion basics (continued)
• Recursive function: a function that calls itself at least once
• Uses modified parameters to shrink the problem with each function call
• Infinite recursion: recursion that fails to reduce the problem size and thus does not
stop; the result of failing to modify the parameters for the recursive function
• Base case: a condition where you should stop trying to solve the problem, such as a
correct solution or a problem small enough to solve quickly
• Sample pseudocode for a recursive function that sums the numbers from 10 to 1:
def add_numbers(n):
if n < 1:
return 0
else:
total = n + add_numbers(n - 1)
return total
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.1 Key Components of Recursion (4 of 7)
• Recursion basics (continued)
• Linear recursion: recursion in which a recursive function calls itself once
• The easiest to program and the most similar to for-loops
• Branching recursion: recursion in which the recursive function calls itself more than
once
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.1 Key Components of Recursion (5 of 7)
Figure 12-4 Linear recursive function
calls (arrows represent actual function
calls)
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.1 Key Components of Recursion (6 of 7)
Figure 12-5 Branching
recursive function calls
(arrows represent actual
function calls)
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.1 Key Components of Recursion (7 of 7)
• When to use recursion
• Consider recursion when a problem can be broken down into smaller problems
• And the smaller problems are identical to the larger problems
• Or there is a way to divide the problem into smaller subproblems that are easy to
solve
• Use loops when you need to do the same thing repeatedly without changing the situation
• Use recursion when you need to reduce the problem to solve it
• Think of recursion as delegating tasks
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Activity 12.1: Knowledge Check
1. A recursive function stops calling itself once it meets a condition known as a(n) _____.
2. If a recursive function needs to return a value, it passes information in a(n) _____.
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Activity 12.1: Knowledge Check Answers
1. A recursive function stops calling itself once it meets a condition known as a(n) _____.
Answer: base case
2. If a recursive function needs to return a value, it passes information in a(n) _____.
Answer: chain
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.2 Using Recursion to Solve Complex Problems
(1 of 7)
• Designing recursive structures
• Checklist for designing a recursive function:
• Check for the base case
• Modify the parameters
• Invoke the function recursively
• Return the result to the calling function
• Anything done in a loop can be done with recursion (but that doesn't mean it should be)
• Recursion may modify parameters incrementally or divide and conquer
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.2 Using Recursion to Solve Complex Problems
(2 of 7)
• Designing recursive structures (continued)
• Program using recursion to identify the user's number:
def guess_number(low, high):
if low > high:
return -1
middle = (low + high) // 2
hint = input("Is your number " + str(middle) + "? ")
if hint == "correct":
return middle
elif hint == "higher":
return guess_number(middle + 1, high)
else:
return guess_number(low, middle - 1)
print("Enter higher, lower, or correct.")
print("Think of a number between 1 and 10.")
number = guess_number(1, 10)
if number != -1:
print("Your number is " + str(number) + "!")
else:
print("You cheated :("
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.2 Using Recursion to Solve Complex Problems
(3 of 7)
Figure 12-7 Loop and recursion to
perform the same task
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.2 Using Recursion to Solve Complex Problems
(4 of 7)
• Linear recursion
• When you can solve a set of smaller problems in sequence, use a loop or linear
recursion
• Sample linear recursive function for adding numbers from 1 to 10:
def add_numbers(current_number):
if current_number > 10:
return 0
else:
next_number = current_number + 1
count = add_numbers(next_number)
return current_number + count
print(add_numbers(1))
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Activity 12.2: Breakout Groups:
Iterator Makeover
1. Form pairs or small groups.
2. Choose two of the loop program examples from Module 7 and modify them to use
recursive functions in place of the loops.
3. Compare the two programs. Which approach is better in each situation, and why?
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.2 Using Recursion to Solve Complex Problems
(5 of 7)
• Branching recursion
• Problems that are more complicated than an iterative design can handle may be solved
with branching recursion
• Functions called by the following sample branching recursive function, which counts files
with a .txt extension in a folder and its subfolders
• os.listdir("folder"): returns a list of files in the folder
• os.path.isdir("filename"): returns True if "filename" is a folder
• os.path.join(["folder", "filename"]): returns a folder name and file
name as a path
• "filename".endswith("extension"): returns True if the file name ends with
the extension
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.2 Using Recursion to Solve Complex Problems
(6 of 7)
Figure 12-11 Recursively counting files
with a .txt extension
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.2 Using Recursion to Solve Complex Problems
(7 of 7)
• Branching recursion (continued)
• The Fibonacci sequence is a weird number sequence defined recursively:
def fibonacci(n):
# Base case
if n == 1 or n == 2:
return 1
# Find the fibonacci number for n – 1
n1 = fibonacci(n - 1)
# Find the fibonacci number for n – 2
n2 = fibonacci(n - 2)
# Add together and return
return n1 + n2
n = int(input("Enter a number: "))
fibonacci_n = fibonacci(n)
print("The Fibonacci number is", fibonacci_n)
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Activity 12.3: Breakout Groups:
Fibonacci Revisited
1. Form pairs or small groups.
2. Try to modify the program in Figure 12-12 so that it asks the user how many items from the
Fibonacci sequence to display, then displays that number of items from the sequence.
3. If you are successful, try to modify it further to display a range of items from the sequence
—e.g., the third through eighth items.
4. What strategies did you choose as you experimented with modifying the program, and
why?
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.3 Managing Memory during Recursion (1 of 6)
• Memory management
• A computer reserves a block of memory to keep track of the current state of the program
• Contains the names of all the program variables along with the values stored in each
variable
• Stacks: data structures that store the memory blocks for recursive function calls
• You only place new blocks on top and can only remove blocks from the top
• The longer a recursive chain of calls, the more memory is needed to keep track of what
happened in the previous calls
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.3 Managing Memory during Recursion (2 of 6)
Figure 12-14 Calling
sum_numbers(10) needs 11 memory
blocks
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.3 Managing Memory during Recursion (3 of 6)
Figure 12-15 Memory stack for
recursive function calls
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.3 Managing Memory during Recursion (4 of 6)
Figure 12-16 Memory stack when
recursive function calls are finished
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.3 Managing Memory During Recursion (5 of 6)
• Stable recursion
• Tail recursion: an approach to recursion that requires zero additional memory on each
function call; the recursive call is placed in the return statement
• Tail recursion rules:
• The recursive call is the last line of code in the function
• The recursive call is in the return statement
• The return statement returns a single value, which is the value from the recursive
call
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
12.3 Managing Memory During Recursion (6 of 6)
Figure 12-17 Using
tail recursion
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Activity 12.4: Knowledge Check
1. When writing a recursive function, you must be sure to indicate when the function should stop looping, modify
the _____, and invoke the function recursively.
2. True or False: Branching recursion is used to solve the same types of problems as loops, whereas linear
recursion is used to tackle problems that are too complicated for an iterative design to handle.
3. Computers use data structures called _____ to store the memory blocks for recursive calls.
4. A function that calls itself multiple times but needs zero additional memory on each function call uses an
approach called _____.
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Activity 12.4: Knowledge Check Answers
1. When writing a recursive function, you must be sure to indicate when the function should stop looping, modify
the _____, and invoke the function recursively.
Answer: parameters
2. True or False: Branching recursion is used to solve the same types of problems as loops, whereas linear
recursion is used to tackle problems that are too complicated for an iterative design to handle.
Answer: False
3. Computers use data structures called _____ to store the memory blocks for recursive calls.
Answer: stacks
4. A function that calls itself multiple times but needs zero additional memory on each function call uses an
approach called _____.
Answer: tail recursion
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Activity 12.5: Discussion
1. Name several specific problems that could be efficiently solved using recursion and identify
the type of recursion they would require (linear or branched). Which could and could not be
readily solved with iterative structures?
2. Choose one of the problems you listed for question 1 and write a pseudocode algorithm for
solving it recursively. Would helper functions be required to assist the recursive function if
you wrote a Python program based on your pseudocode?
3. Rewrite either your pseudocode from question 2 or one of the example programs from
Module 12 (other than the one shown in Figure 12-17) to use tail recursion.
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Self-Assessment
1. When faced with a programming task where either approach would work, do you have a
preference for either iterative control structures or recursive designs for your code? Explain
why or why not.
2. Do you find recursive functions easy to understand, challenging to follow, or somewhere in
between? Do you enjoy planning and coding a recursive function?
McMullen/Matthews/Parsons, Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Summary
Click the link to review the objectives for this presentation.
Link to Objectives

McMullen_ProgwPython_1e_mod12_PowerPoint.pptx

  • 1.
    Programming with Python McMullen/Matthews/Parsons,Programming with Python, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Module 12: Recursion
  • 2.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Module Objectives (1 of 2) • 12.1 Key Components of Recursion • 12.1.1 Define recursion as a problem-solving approach. • 12.1.2 Describe the purpose of recursion. • 12.1.3 Explain the components of a recursive function. • 12.1.4 List advantages and disadvantages of recursion. • 12.2 Using Recursion To Solve Complex Problems • 12.2.1 Explain the application of recursion. • 12.2.2 Differentiate recursive algorithms from algorithms that use repetition control structures. • 12.2.3 Define the “divide and conquer” approach to problem solving. • 12.2.4 Analyze how to use a base case and a recursive case to implement recursion into an iterative programming solution. • 12.2.5 Construct a procedural program using recursion.
  • 3.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Module Objectives (2 of 2) • 12.3 Managing Memory During Recursion • 12.3.1 Explain memory management and its importance with recursion. • 12.3.2 Explain the use of a stack during recursion. • 12.3.3 Explain tail-recursive functions.
  • 4.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.1 Key Components of Recursion (1 of 7) • The recursive mindset • Recursion is the problem-solving approach that divides large problems into smaller, identical problems • The same steps are applied to each smaller version of the problem, although with different restrictions • Recursion basics • Recursion solves problems using functions, which: • Are named blocks of code that perform a specific task • Can have information passed to them as parameters • Can return information as return values, which can be used for calculations and other operations • Can be called to execute the lines of code inside the function • Can call other functions
  • 5.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.1 Key Components of Recursion (2 of 7) Figure 12-3 Guessing game using function calls
  • 6.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.1 Key Components of Recursion (3 of 7) • Recursion basics (continued) • Recursive function: a function that calls itself at least once • Uses modified parameters to shrink the problem with each function call • Infinite recursion: recursion that fails to reduce the problem size and thus does not stop; the result of failing to modify the parameters for the recursive function • Base case: a condition where you should stop trying to solve the problem, such as a correct solution or a problem small enough to solve quickly • Sample pseudocode for a recursive function that sums the numbers from 10 to 1: def add_numbers(n): if n < 1: return 0 else: total = n + add_numbers(n - 1) return total
  • 7.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.1 Key Components of Recursion (4 of 7) • Recursion basics (continued) • Linear recursion: recursion in which a recursive function calls itself once • The easiest to program and the most similar to for-loops • Branching recursion: recursion in which the recursive function calls itself more than once
  • 8.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.1 Key Components of Recursion (5 of 7) Figure 12-4 Linear recursive function calls (arrows represent actual function calls)
  • 9.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.1 Key Components of Recursion (6 of 7) Figure 12-5 Branching recursive function calls (arrows represent actual function calls)
  • 10.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.1 Key Components of Recursion (7 of 7) • When to use recursion • Consider recursion when a problem can be broken down into smaller problems • And the smaller problems are identical to the larger problems • Or there is a way to divide the problem into smaller subproblems that are easy to solve • Use loops when you need to do the same thing repeatedly without changing the situation • Use recursion when you need to reduce the problem to solve it • Think of recursion as delegating tasks
  • 11.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Activity 12.1: Knowledge Check 1. A recursive function stops calling itself once it meets a condition known as a(n) _____. 2. If a recursive function needs to return a value, it passes information in a(n) _____.
  • 12.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Activity 12.1: Knowledge Check Answers 1. A recursive function stops calling itself once it meets a condition known as a(n) _____. Answer: base case 2. If a recursive function needs to return a value, it passes information in a(n) _____. Answer: chain
  • 13.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.2 Using Recursion to Solve Complex Problems (1 of 7) • Designing recursive structures • Checklist for designing a recursive function: • Check for the base case • Modify the parameters • Invoke the function recursively • Return the result to the calling function • Anything done in a loop can be done with recursion (but that doesn't mean it should be) • Recursion may modify parameters incrementally or divide and conquer
  • 14.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.2 Using Recursion to Solve Complex Problems (2 of 7) • Designing recursive structures (continued) • Program using recursion to identify the user's number: def guess_number(low, high): if low > high: return -1 middle = (low + high) // 2 hint = input("Is your number " + str(middle) + "? ") if hint == "correct": return middle elif hint == "higher": return guess_number(middle + 1, high) else: return guess_number(low, middle - 1) print("Enter higher, lower, or correct.") print("Think of a number between 1 and 10.") number = guess_number(1, 10) if number != -1: print("Your number is " + str(number) + "!") else: print("You cheated :("
  • 15.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.2 Using Recursion to Solve Complex Problems (3 of 7) Figure 12-7 Loop and recursion to perform the same task
  • 16.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.2 Using Recursion to Solve Complex Problems (4 of 7) • Linear recursion • When you can solve a set of smaller problems in sequence, use a loop or linear recursion • Sample linear recursive function for adding numbers from 1 to 10: def add_numbers(current_number): if current_number > 10: return 0 else: next_number = current_number + 1 count = add_numbers(next_number) return current_number + count print(add_numbers(1))
  • 17.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Activity 12.2: Breakout Groups: Iterator Makeover 1. Form pairs or small groups. 2. Choose two of the loop program examples from Module 7 and modify them to use recursive functions in place of the loops. 3. Compare the two programs. Which approach is better in each situation, and why?
  • 18.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.2 Using Recursion to Solve Complex Problems (5 of 7) • Branching recursion • Problems that are more complicated than an iterative design can handle may be solved with branching recursion • Functions called by the following sample branching recursive function, which counts files with a .txt extension in a folder and its subfolders • os.listdir("folder"): returns a list of files in the folder • os.path.isdir("filename"): returns True if "filename" is a folder • os.path.join(["folder", "filename"]): returns a folder name and file name as a path • "filename".endswith("extension"): returns True if the file name ends with the extension
  • 19.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.2 Using Recursion to Solve Complex Problems (6 of 7) Figure 12-11 Recursively counting files with a .txt extension
  • 20.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.2 Using Recursion to Solve Complex Problems (7 of 7) • Branching recursion (continued) • The Fibonacci sequence is a weird number sequence defined recursively: def fibonacci(n): # Base case if n == 1 or n == 2: return 1 # Find the fibonacci number for n – 1 n1 = fibonacci(n - 1) # Find the fibonacci number for n – 2 n2 = fibonacci(n - 2) # Add together and return return n1 + n2 n = int(input("Enter a number: ")) fibonacci_n = fibonacci(n) print("The Fibonacci number is", fibonacci_n)
  • 21.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Activity 12.3: Breakout Groups: Fibonacci Revisited 1. Form pairs or small groups. 2. Try to modify the program in Figure 12-12 so that it asks the user how many items from the Fibonacci sequence to display, then displays that number of items from the sequence. 3. If you are successful, try to modify it further to display a range of items from the sequence —e.g., the third through eighth items. 4. What strategies did you choose as you experimented with modifying the program, and why?
  • 22.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.3 Managing Memory during Recursion (1 of 6) • Memory management • A computer reserves a block of memory to keep track of the current state of the program • Contains the names of all the program variables along with the values stored in each variable • Stacks: data structures that store the memory blocks for recursive function calls • You only place new blocks on top and can only remove blocks from the top • The longer a recursive chain of calls, the more memory is needed to keep track of what happened in the previous calls
  • 23.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.3 Managing Memory during Recursion (2 of 6) Figure 12-14 Calling sum_numbers(10) needs 11 memory blocks
  • 24.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.3 Managing Memory during Recursion (3 of 6) Figure 12-15 Memory stack for recursive function calls
  • 25.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.3 Managing Memory during Recursion (4 of 6) Figure 12-16 Memory stack when recursive function calls are finished
  • 26.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. © 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.3 Managing Memory During Recursion (5 of 6) • Stable recursion • Tail recursion: an approach to recursion that requires zero additional memory on each function call; the recursive call is placed in the return statement • Tail recursion rules: • The recursive call is the last line of code in the function • The recursive call is in the return statement • The return statement returns a single value, which is the value from the recursive call
  • 27.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. 12.3 Managing Memory During Recursion (6 of 6) Figure 12-17 Using tail recursion
  • 28.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Activity 12.4: Knowledge Check 1. When writing a recursive function, you must be sure to indicate when the function should stop looping, modify the _____, and invoke the function recursively. 2. True or False: Branching recursion is used to solve the same types of problems as loops, whereas linear recursion is used to tackle problems that are too complicated for an iterative design to handle. 3. Computers use data structures called _____ to store the memory blocks for recursive calls. 4. A function that calls itself multiple times but needs zero additional memory on each function call uses an approach called _____.
  • 29.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Activity 12.4: Knowledge Check Answers 1. When writing a recursive function, you must be sure to indicate when the function should stop looping, modify the _____, and invoke the function recursively. Answer: parameters 2. True or False: Branching recursion is used to solve the same types of problems as loops, whereas linear recursion is used to tackle problems that are too complicated for an iterative design to handle. Answer: False 3. Computers use data structures called _____ to store the memory blocks for recursive calls. Answer: stacks 4. A function that calls itself multiple times but needs zero additional memory on each function call uses an approach called _____. Answer: tail recursion
  • 30.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Activity 12.5: Discussion 1. Name several specific problems that could be efficiently solved using recursion and identify the type of recursion they would require (linear or branched). Which could and could not be readily solved with iterative structures? 2. Choose one of the problems you listed for question 1 and write a pseudocode algorithm for solving it recursively. Would helper functions be required to assist the recursive function if you wrote a Python program based on your pseudocode? 3. Rewrite either your pseudocode from question 2 or one of the example programs from Module 12 (other than the one shown in Figure 12-17) to use tail recursion.
  • 31.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Self-Assessment 1. When faced with a programming task where either approach would work, do you have a preference for either iterative control structures or recursive designs for your code? Explain why or why not. 2. Do you find recursive functions easy to understand, challenging to follow, or somewhere in between? Do you enjoy planning and coding a recursive function?
  • 32.
    McMullen/Matthews/Parsons, Programming withPython, 1st Edition. Š 2023 Cengage. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Summary Click the link to review the objectives for this presentation. Link to Objectives