Final challenge: the frame detective
After this: Read a stack during a run, fix a missing base case, change a recursion into a loop, and count calls.
This challenge has four steps, and each step is scored on its own. You will read the call stack at one moment of a run, fix a function that never stops, replace a recursive call with a push on a stack, and count the calls of a function that calls itself twice. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 4Trace it
Trace it
factorial(4) is running. factorial(1) has been pushed and has not made its smaller call yet. What is on the call stack, top first?
Fix the base case
power(2, 3) should return 8, but this version never returns. Which first line fixes it for every exponent from 0 upwards?
def power(base, exp): return base * power(base, exp - 1) # exp shrinks, but nothing ever says stop
print(power(2, 3))static int power(int base, int exp) { return base * power(base, exp - 1); // exp shrinks, but nothing ever says stop}
System.out.println(power(2, 3));Convert to a loop
total_iterativetotalIterative replaces the recursive call with a stack of lists still to visit. Complete the line that deals with an inner list.
def total_iterative(items): result = 0 stack = [items] # lists still to visit while stack: current = stack.pop() for x in current: if isinstance(x, list): ______________________ # ← the loop's replacement for the recursive call else: result += x return resultstatic int totalIterative(List<?> items) { int result = 0; Deque<List<?>> stack = new ArrayDeque<>(); // lists still to visit stack.push(items); while (!stack.isEmpty()) { List<?> current = stack.pop(); for (Object x : current) { if (x instanceof List<?> inner) { ______________________ // ← the loop's replacement for the recursive call } else { result += (Integer) x; } } } return result;}Count the calls
Each call makes two smaller calls, both with n − 1. What does this print?
calls = 0
def ways(n): global calls calls += 1 if n == 0: return 1 return ways(n - 1) + ways(n - 1)
print(ways(3), calls)static int calls = 0;
static int ways(int n) { calls++; if (n == 0) return 1; return ways(n - 1) + ways(n - 1);}
System.out.println(ways(3) + " " + calls);- Read a call stack during a run, fix a missing base case, replace a recursive call with a push, and count the calls of a function that calls itself twice.