pythonadvanced15 minutes

Build a High-Performance Memoized Fibonacci Function with Custom Cache Size

Create an advanced Python function to compute Fibonacci numbers using memoization with a customizable cache size limit, evicting oldest cached values when the cache exceeds the limit. The function should be optimized for both speed and memory usage.

Challenge prompt

Build a function named `fib_memo` that computes the nth Fibonacci number efficiently using memoization. The function should accept two arguments: `n` (the index) and an optional `cache_size` which limits the size of the memoization cache. When the number of cached entries exceeds `cache_size`, your function should evict the oldest cached value before adding a new one to keep the cache size bounded. Default `cache_size` should be 100. Your solution must handle very large n efficiently and explicitly manage the cache as a fixed-size LRU (Least Recently Used) cache without using external libraries.

Guidance

  • Use a dictionary or OrderedDict to store cached Fibonacci values.
  • Implement your own logic to track the order of cache usage to know which entry to evict when exceeding cache_size.
  • Optimize recursive calls by checking the cache to avoid recalculations.

Hints

  • Consider using collections.OrderedDict to maintain insertion order and facilitate LRU eviction.
  • You can update the position of a cache entry every time it is accessed to reflect recent use.
  • Be careful with the base cases for Fibonacci (0 and 1).

Starter code

def fib_memo(n, cache_size=100):
    # Your implementation here
    pass

Expected output

fib_memo(10) -> 55 fib_memo(50) -> 12586269025 fib_memo(100) -> 354224848179261915075

Core concepts

memoizationLRU cacherecursiondictionary managementalgorithm optimization

Challenge a Friend

Send this duel to someone else and see if they can solve it.