CodexBloom - Programming Q&A Platform

implementing Fibonacci Sequence Optimization in Python - Unexpected Results with Memoization

πŸ‘€ Views: 93 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-22
python optimization memoization Python

Could someone explain I've hit a wall trying to I'm currently trying to optimize a recursive solution for calculating Fibonacci numbers using memoization in Python, but I'm working with unexpected results. When I call my `fibo` function with an input of `10`, I expect to get `55`, but I'm getting `50` instead. Here's the code I'm using: ```python class Fibonacci: def __init__(self): self.memo = {} def fibo(self, n): if n <= 1: return n if n not in self.memo: self.memo[n] = self.fibo(n - 1) + self.fibo(n - 2) return self.memo[n] fib = Fibonacci() print(fib.fibo(10)) # This should print 55 ``` I've verified that my base cases are correct. I also tried printing the values stored in `self.memo` at various points to debug, and they appear to be adding correctly up to `n=5`, but then seem to diverge afterward. I'm using Python 3.8.10, and I don’t think there are any issues with the Python installation itself since other parts of my code run fine. Is there something I'm missing in the implementation? Could it be related to how I'm checking for existing keys in the dictionary? Any help would be appreciated! I'd be grateful for any help. What's the correct way to implement this?