These questions follow Recursion. Every answer below is marked on two things before anything else: is there a base case, and does every call get closer to it. Write those two lines first, every time.

Reading

  1. Predict the output, and say what the function computes.
    def mystery(n):
        if n == 0:
            return 0
        return n + mystery(n - 1)
     
    print(mystery(4))
  2. Find the fault. This runs, prints a lot, and then stops badly. What is missing, what exactly does Python say, and why is raising the recursion limit the wrong fix?
    def countdown(n):
        print(n)
        countdown(n - 1)
     
    countdown(3)
  3. Find the fault. This one has a base case and still never reaches it. Why?
    def count_down_by_two(n):
        if n == 0:
            return "done"
        return count_down_by_two(n - 2)
     
    print(count_down_by_two(7))

Writing

  1. Write sum_to(n), returning recursively, with sum_to(0) as the base case. Check it on 5, 0, and 100.
  2. Write countdown(n), printing n down to 1 and then Go.
  3. Write total_of(items), which adds up numbers in a list that may contain other lists, to any depth. Test it on [1, [2, 3, [4]], 5] and on [].
  4. Write backwards(text) recursively, and say what your base case does with the empty string.
  5. Write power(base, exponent) recursively for exponents of zero or more.
  6. Cost. Rewrite fib so that it returns both the answer and the number of calls it made, then report the counts for n of 5, 10, 20, and 25. Explain the growth, and write the loop version that does not have the problem.
  7. Theoretical foundations. Write the recurrence relations for sum_to(n) and for naive fib(n). Explain how mathematical induction proves that a recursive function with a correct base case terminates for all legal inputs, and how the call stack depth governs auxiliary space complexity.

Answers

Curriculum connection

A3.6

design a simple and efficient recursive algorithm (e.g., calculate a factorial, translate numbers into words, perform a merge sort, generate fractals, perform XML parsing).

Link to original

C1.3

demonstrate the ability to apply the process of functional decomposition in subprogram design;

Link to original

C2.4

identify common pitfalls in recursive functions (e.g., infinite recursion, exponential growth in recursive algorithms such as Fibonacci numbers).

Link to original

D4.2

investigate a topic in theoretical computer science (e.g., cryptography, graph theory, logic, computability theory, attribute grammar, automata theory, data mining, artificial intelligence, robotics, computer vision, image processing), and produce a report, using an appropriate format (e.g., website, presentation software, video);

Link to original