1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 1

CAP7004 · Unit 1: Python foundations and analysis

Recursion

8 practice questions

Key points

  • Needs a base case and progress toward it
  • Each call uses a stack frame; default limit 1000
  • Naive Fibonacci is exponential; memoize
  • Hanoi needs 2^n - 1 moves

A recursive function solves a problem by calling itself on a smaller instance. Every recursion needs:

  1. a base case that stops the calls, and
  2. a recursive case that moves toward the base case.
def fact(n):
    return 1 if n <= 1 else n * fact(n - 1)

Each call adds a stack frame. Python's default recursion limit is 1000; deeper recursion raises RecursionError. Missing or unreachable base cases cause infinite recursion.

Costs:

  • fact(n): n calls, O(n) time and O(n) stack space.
  • Naive fib(n) = fib(n-1) + fib(n-2): exponential time (fib(10) makes 177 calls) because subproblems repeat; memoization fixes it.
  • Divide-by-2 recursion such as fast power pw(x, n) or binary search: O(log n) calls.
  • Tower of Hanoi with n discs needs 2^n - 1 moves.

Recursion versus iteration: every recursion can be turned into a loop (possibly with an explicit stack); recursion is shorter for trees and divide-and-conquer.

Try two questions

Question 1 · Tier 3, Apply

Why is naive recursive Fibonacci slow?

  1. It has no base case
  2. It uses too many global variables
  3. Python cannot recurse twice per call
  4. It recomputes the same subproblems many times
Show the answer

D. Overlapping subproblems cause exponentially many calls (177 for fib(10)).

Question 2 · Tier 2, Understand

With fib(0)=0 and fib(1)=1, fib(9) equals:

  1. 21
  2. 55
  3. 13
  4. 34
Show the answer

D. The sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.