Unexpected Time Complexity in Recursive Fibonacci Calculation with Memoization in Python
I'm not sure how to approach I just started working with I recently switched to I'm working on a Fibonacci sequence calculation in Python using a recursive approach with memoization, but I've noticed that the performance is not as expected... The algorithm is supposed to run in linear time due to memoization, but I'm seeing a significant delay when calculating Fibonacci numbers for inputs greater than 30. Hereβs the code I have: ```python class Fibonacci: def __init__(self): self.memo = {} def fib(self, n): if n in self.memo: return self.memo[n] if n <= 1: return n self.memo[n] = self.fib(n - 1) + self.fib(n - 2) return self.memo[n] fibonacci = Fibonacci() print(fibonacci.fib(35)) # Intending to print 9227465 ``` When I run the above code with `fibonacci.fib(35)`, it takes several seconds to compute the result, which doesn't align with the expected O(n) time complexity I was aiming for. Iβve ensured that memoization is properly implemented since Iβm caching results in a dictionary. I even added print statements to see how many times the function is called: ```python def fib(self, n): print(f"Calculating fib({n})") # Debug line ``` This shows that the function is being called multiple times for the same `n` values, which should not happen with memoization. I tried using a different approach by implementing an iterative solution: ```python def fib_iterative(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return a ``` The iterative version executes as expected, but I want to understand why the recursive approach with memoization is not performing as anticipated. Any insights or suggestions would be greatly appreciated! This is my first time working with Python LTS. Any examples would be super helpful. Any suggestions would be helpful. Thanks, I really appreciate it!