Module 30: Advanced Recursion

Deepen your understanding of recursive thinking.

Predict the Output

Read the recursive function below. What will be the exact output (including the final return value printed) when `print(factorial(3))` is called? Type your prediction.

def factorial(n):
    # Base case
    if n <= 1:
        return 1
    # Recursive step
    else:
        return n * factorial(n - 1)

# What does this print?
print(factorial(3))

Spot the Recursive Call

The essence of recursion is the function calling itself. Click on the line(s) below that contain a recursive call. Then click "Check Selection".

Advanced Simulator: Power Function

Write a recursive function `power(base, exp)` that calculates `base` raised to the power of `exp` (where `exp >= 0`). Remember the base case! Then, print the result of `power(2, 4)`.

Output will appear here...

Advanced Mini Missions!

Tackle these more complex recursive challenges!

Mission 1: Recursive List Sum

Write a recursive function `sum_list(data)` that takes a list of numbers `data` and returns their sum. Hint: Sum the first element with the recursive sum of the rest of the list (`data[1:]`). Base case: empty list.

Mission 2: Fibonacci Sequence

Write a recursive function `fibonacci(n)` that returns the nth Fibonacci number (0, 1, 1, 2, 3, 5, 8...). Base cases: `fibonacci(0) = 0`, `fibonacci(1) = 1`. Recursive step involves *two* calls. Print the result of `fibonacci(6)`.

Mission 3: Reverse String Recursively

Write a recursive function `reverse_string(s)` that returns the reversed version of string `s`. Hint: Return the reversed rest of the string (`s[1:]`) concatenated with the first character (`s[0]`). Base case: empty string.

Module 30 Advanced Practice Complete!

Excellent work tackling these recursive challenges! You're building strong problem-solving skills.