#!/usr/bin/env python3 """ Scenario 2: Hidden Redundancy - The Memoization Problem ======================================================== This program computes Fibonacci numbers recursively. The naive implementation has exponential time complexity due to redundant calls. EXERCISES: 1. Run: time python3 fib_slow.py 35 2. Profile: python3 -m cProfile -s ncalls fib_slow.py 35 3. Notice the HUGE number of calls to fib() 4. See fib_cached.py for the memoized version """ import sys def fib(n): """Compute the nth Fibonacci number recursively.""" if n <= 1: return n return fib(n - 1) + fib(n - 2) def main(): n = 35 # Don't go much higher without optimization! if len(sys.argv) > 1: n = int(sys.argv[1]) print(f"Computing fib({n})...") result = fib(n) print(f"fib({n}) = {result}") if __name__ == "__main__": main()