CodexBloom - Programming Q&A Platform

Handling Time Complexity in Recursive Fibonacci with Memoization in Python - Stack Overflow scenarios

πŸ‘€ Views: 44 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
python recursion memoization Python

I'm collaborating on a project where I've been struggling with this for a few days now and could really use some help. I'm reviewing some code and I'm integrating two systems and I'm relatively new to this, so bear with me. I'm stuck on something that should probably be simple. I'm currently implementing a Fibonacci sequence generator using recursion with memoization in Python, aiming to optimize the performance for larger input values. However, when I try to compute the 1000th Fibonacci number, I'm working with a `RecursionError: maximum recursion depth exceeded in comparison`. I understand that the default recursion limit might be too low for deep recursive calls, but I'm concerned about whether my approach is still efficient and adheres to best practices. Here's my current implementation: ```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(1000)) ``` I've tried increasing the recursion limit using `sys.setrecursionlimit()`, but that feels like more of a workaround than a solution. I'd like to confirm whether memoization is correctly implemented and if there’s a better way to calculate Fibonacci numbers without hitting the recursion limit. Additionally, is there a more efficient approach that avoids the pitfalls of recursion entirely? Any guidance on this would be greatly appreciated! How would you solve this? What am I doing wrong? Thanks for your help in advance! For reference, this is a production mobile app. What are your experiences with this?