Functools LRU Cache in Python
Level 5317 keystrokes
This uses @lru_cache decorator to memoize function results, dramatically speeding up recursive calculations.
Python code
# Import lru_cache for memoization1from functools import lru_cache# Import time for measuring execution2import time3 # Apply LRU cache with max 128 entries4@lru_cache(maxsize=128)# Define recursive Fibonacci function5def fibonacci(n): # Base case: return n for 0 or 16 if n < 2: # Return the base value7 return n # Recursive case: sum of two previous numbers8 return fibonacci(n - 1) + fibonacci(n - 2)9 # Record start time10start = time.time()# Calculate fibonacci(35) - cached calls are instant11result = fibonacci(35)# Record end time12end = time.time()13 # Print the result14print(f"fib(35) = {result}")# Print execution time15print(f"Time: {end - start:.4f}s")# Print cache statistics (hits, misses, size)16print(f"Cache: {fibonacci.cache_info()}")Output
fib(35) = 9227465 Time: 0.0001s Cache: CacheInfo(hits=33, misses=36, maxsize=128, currsize=36)
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.
(× 12)× 12"× 6:× 5=× 5.× 4_× 3-× 3{× 3}× 3