Lecture 7 Recursion
- Question
- Going over how the Luhn Sum function works
- sum_digits_rec, still unsure about how it works
- Analogy - Place in Line
- Ask the person in front, how many people are in front of you
- Recursive Functions
- A function is called recursive if the body of that function calls itself, either directly or indirectly
- May require applying that function
- Recursive Call Structure
- Base case(s)
- simplest instance of the problem can be solved without much work
- the trueism - no other work needed
- The first person knows their first in line
- Recursive Call
- making a call to the same function with a smaller input
- How many people in front of you?
- Recombination
- Using the result of the recursive call to solve the original problem
- Example: Factorial
- To solve Factorial of 5, solve factorial of 4 * 5
- Base cases
- think about the edges of our domain
- Example: Sum Digits
- We can break the problem of summing the digits of 2023 into a smaller instance of the same problem, plus extra stuff
- Solving 2023
- sum_digits(202) + 3
- Use a split function to help
- returns the number split into parts
- Anatomy of a Recursive Function
- Def statement header is similar to other functions
- Conditional statements check for base cases
- base cases evaluated without recursive calls
- Recursive cases are evaluated with recursive calls
- Recursion in Environment Diagrams
- Every time you call a function you open a new frame
- Iteration vs Recursion
- Recursion
- keep track of value in the arguments of the function
- Verifying Recursive Functions
- The Recursive Leap of Faith
- Is fact implemented correctly?
- Verify the base case
- Treat fact as a functional abstraction
- Assume that fact(n-1) is correct
- Verify that fact(n) is correct
- Mutual Recursion
- The Luhn Algorithm
- Rightmost digit, check digits moving left, doubling each number, sum #s > 10’s digits
- Take the sum of all digits
- Two functions calling each other
- Luhn sum calls luhn sum double
- Luhn sum double calls Luhn sum
- More Examples
- Implementing a Function
- Read the description
- Verify the examples and pick a simple one
- Read the template
- Annotate names with values from your chosen example
- Write code to compute the result
- Remove function
- base case: 0
- Converting Recursion to Iteration
- Figure out what state must be maintained by the iterative function
- Summary
- Anatomy of Recursive functions
- base case
- recursive case
- recombination
- Mutual recursion
- Relationship between iteration and recursion
- Implementing recursive functions