12.1 Recursion basics

3 min readjune 24, 2024

is a powerful programming technique that breaks complex problems into simpler subproblems. By calling a function within itself, recursion solves each subproblem until reaching a , then combines the results to solve the original problem.

Writing recursive functions requires careful consideration of base cases and recursive cases. Tracing recursive algorithm execution helps understand how the function works, while optimization techniques like can improve performance. Recursion is a valuable tool for solving complex problems efficiently.

Recursion Fundamentals

Recursion for problem simplification

Top images from around the web for Recursion for problem simplification
Top images from around the web for Recursion for problem simplification
  • Recursion breaks down complex problems into simpler subproblems
    • Divides original problem into smaller, more manageable parts
    • Solves each subproblem recursively by calling the same function
    • Combines solutions of subproblems to solve the original problem
  • Recursive functions consist of two main components:
    • Base case: simple, non-recursive condition that terminates recursion (empty list, zero, one)
    • Recursive case: condition that calls the function itself with a simpler input (smaller list, reduced number)
  • Calculating of a number nn recursively (4!, 5!)
    • Factorial of nn defined as n!=n×(n1)×(n2)×...×2×1n! = n \times (n-1) \times (n-2) \times ... \times 2 \times 1
    • Base case: n=0n = 0 or n=1n = 1, factorial is defined as 1
    • Recursive case: breaks down problem into simpler version by calculating n!=n×(n1)!n! = n \times (n-1)!
  • Recursion often employs a strategy to solve problems

Writing recursive functions

  • Recursive functions must have a base case to avoid
    • Base case: condition that causes function to without further recursive calls
    • Typically the simplest possible input for the function (empty list, zero, one)
  • Recursive case: function calls itself with a modified input
    • Modified input should move closer to base case with each recursive call (smaller list, reduced number)
    • Ensures function will eventually reach base case and terminate
  • Recursive function to calculate sum of numbers from 1 to nn
[def](https://www.fiveableKeyTerm:def) sum_recursive(n):
    if n == 1:  # Base case
        return 1
    else:  # Recursive case
        return n + sum_recursive(n - 1)
  • is a specific form where the recursive call is the last operation in the function

Tracing recursive algorithm execution

  • Tracing execution helps understand how recursive function works
    • Keeps track of each function call and corresponding return value
    • Function calls represented in a , most recent call at the top
  • When recursive function called, added to top of call stack
    • If base case met, function returns value and is removed from stack
    • If recursive case met, new function call added to top of stack
  • Return values passed back through call stack as each function call completes
  • Tracing execution of recursive factorial function for n=4n = 4
factorial(4)
  ├── 4 * factorial(3)
         ├── 3 * factorial(2)
                ├── 2 * factorial(1)
                       ├── 1 (base case)
                ├── 2 * 1 = 2
         ├── 3 * 2 = 6
  ├── 4 * 6 = 24

Optimization and Performance Considerations

  • Recursion can lead to errors if the call stack becomes too large
  • Memoization can improve performance by storing results of expensive function calls
  • is often an alternative to recursion, potentially offering better performance in some cases

Key Terms to Review (15)

Base Case: A base case is a fundamental concept in recursion that acts as a stopping point for recursive functions. It defines the simplest instance of a problem that can be solved directly without further recursion, ensuring that the recursion does not continue indefinitely. Understanding base cases is essential for effectively implementing recursion in algorithms, particularly when tackling mathematical problems, processing strings and lists, or solving complex challenges.
Call Stack: The call stack is a fundamental concept in computer programming that refers to the mechanism used by the computer's processor to keep track of the active subroutines (functions) in a program. It is a stack data structure that stores information about the active subroutines of a computer program.
Def: The 'def' keyword in Python is used to define a function, which is a reusable block of code that performs a specific task. Functions allow programmers to break down complex problems into smaller, more manageable parts, making the code more organized, efficient, and easier to maintain.
Divide and Conquer: Divide and conquer is a problem-solving strategy that involves breaking a complex problem into smaller, more manageable sub-problems, solving each sub-problem independently, and then combining the solutions to solve the original problem. This approach is often used in computer science, mathematics, and other fields to tackle complex problems efficiently.
Factorial: The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is a fundamental concept in mathematics, with applications in various fields, including computer science, probability, and combinatorics.
If-else statements: If-else statements are a fundamental control structure in programming that allow for decision-making based on conditions. They enable the execution of different code blocks depending on whether a specified condition evaluates to true or false. This type of conditional logic is crucial for managing the flow of a program, making it possible to handle various scenarios, especially in areas like recursion and data analysis.
Infinite Recursion: Infinite recursion refers to a situation in computer programming where a function or algorithm repeatedly calls itself without a termination condition, leading to an endless loop that never completes. This can result in a program crashing or consuming an excessive amount of system resources, making it an important concept to understand in the context of recursion basics.
Iteration: Iteration is the process of repeating a set of instructions or operations multiple times in a computer program or algorithm. It is a fundamental concept in programming that allows for the execution of a block of code repeatedly until a specific condition is met.
Memoization: Memoization is an optimization technique that involves storing the results of expensive function calls and returning the cached result when the same inputs occur again. This helps to avoid redundant calculations and improves the overall efficiency of a program.
Recursion: Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. It typically involves a base case to terminate the recursive calls and prevent infinite loops.
Return: The term 'return' in programming refers to the action of a function or method sending a value back to the code that called it. It is a fundamental concept that allows functions to communicate with the rest of a program, providing useful output or results based on the input they receive.
Return statement: A return statement is used in a function to send a result back to the caller. It terminates the execution of the function and can optionally pass back an expression or value.
Stack overflow: A stack overflow occurs when a program uses more memory on the call stack than is available, typically due to excessive recursion or infinite loops. It happens when the program makes too many function calls without returning, leading to the exhaustion of the call stack's allocated memory space. This concept is important in understanding how recursive functions work and the potential issues that can arise when they are not properly managed.
Sum_recursive(): sum_recursive() is a recursive function that calculates the sum of all elements in a list or array by repeatedly calling itself with a smaller subset of the original data until the base case is reached. It is a fundamental concept in understanding recursion, a programming technique where a function calls itself to solve a problem.
Tail Recursion: Tail recursion is a special type of recursion where the recursive call is the last operation performed by the function. This means that the recursive call is the final step, and the function does not need to do any additional processing after the recursive call completes.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary