Fibonacci pitfalls: branching work

Intermediate Recursion & structural decomposition
Created by Pavel · 29.04.2026 at 19:04 UTC

The one-liner fib(n) = fib(n-1) + fib(n-2) is a famous trap: it is correct as mathematics and catastrophic as an algorithm because each call fans out into two calls that recompute the same subproblems exponentially many times. Students paste it into notebooks, wait, and conclude that “Python is slow”—the real issue is redundant work, not the interpreter.

In production data code you meet the same pattern under different names: naive dynamic-programming formulations without a table, recomputing rolling statistics inside nested loops, or evaluating the same expensive feature transform on overlapping slices. The fixes are the same family: iterate with constant memory, memoise with a dict or functools.lru_cache, or move the hot loop into a vectorised kernel.

Asymptotic growth matters more than micro-optimising a constant factor: exponential time blows up long before you need a bigger machine.

functools.lru_cache documentation: [1].


Sources

University approvals: 0
Tasks
Question 1

Rough time complexity for def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)?

Hint

Each call spawns two overlapping subcalls.

Question 2

A colleague profiles a pandas pipeline and finds a Python for loop that recomputes the same group statistics for overlapping windows. Which mindset matches the Fibonacci pitfall?

Hint

Think redundant work, not just loop overhead.

Question 3

Rewrite Fibonacci iteratively (no recursion): fib(0)==0, fib(1)==1; for n>=2, usual recurrence. For n < 0 raise ValueError. Stdlib only.
Implement fib(iter_n: int) -> int.

Hint

Track two successive values in a loop of length n.

Starter code is prefilled; replace TODO blocks with your solution.
2 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Recursion & structural decomposition
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Pavel
Pavel