LRU Cache Decorator in Python
Level 5224 keystrokes
This uses lru_cache decorator to memoize function results. The cache stores recent results to avoid redundant calculations.
Python code
# Import lru_cache from functools1from functools import lru_cache2 # Apply LRU cache decorator with max 128 entries3@lru_cache(maxsize=128)# Define recursive fibonacci function4def fibonacci(n): # Base case: return n for 0 or 15 if n < 2: # Return n directly6 return n # Recursive case: sum of two previous fibonacci numbers7 return fibonacci(n - 1) + fibonacci(n - 2)8 # Print first 10 fibonacci numbers9for i in range(10): # Print each number followed by space10 print(fibonacci(i), end=" ")# Print newline11print()# Print cache statistics12print(fibonacci.cache_info())Output
0 1 1 2 3 5 8 13 21 34 CacheInfo(hits=16, misses=10, maxsize=128, currsize=10)
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 10)× 10_× 3:× 3-× 2"× 2=× 2,× 1.× 1@× 1