Recursion is a way to solve a problem by having a function call itself on a smaller version of that problem. This lesson uses factorials, sums, and digit sums to show how recursive solutions work and how they stop safely.
Without a base case, calls may continue indefinitely, causing an error such as Python's maximum recursion depth error.
Definition: A recursive case reduces a problem by calling the function again. A base case is a situation whose answer is already known and that ends the recursion.
All flashcards
What is recursion?
Recursion is a problem-solving approach in which a function calls itself, typically on a smaller or simpler input.
How do the recursive case and base case differ?
The recursive case makes progress by calling the function again on a reduced problem. The base case returns a known answer and ends the calls.
What is the recursive definition of factorial?
For n>1,n!=n×(n−1)!. The base values include 0!=1 and 1!=1.
How can a recursive function sum integers from 0 through n?
Use S(0)=0 as the base case and, for n>0, return n+S(n−1).
How does recursion sum the digits of a nonnegative integer?
Add the last digit, found with `n % 10`, to the digit sum of the remaining number, found with `n // 10`. Stop when the number has one digit.
Quiz questions
What is the role of a base case in a recursive function?Answer: It returns a known result and ends further recursive calls.
What value does a function that sums integers from 0 through n return for n = 4?Answer: 10
What does `digit_sum(6721)` return when the function adds the digits of a nonnegative integer?Answer: 16
For a nonnegative integer, what does `n // 10` do in a decimal digit-sum function?Answer: Removes the final decimal digit from the integer.
When a recursive factorial calculation reaches its base case, how are the pending results combined?Answer: Each returning call multiplies its input by the smaller factorial result.
Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.