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 memoization
1from functools import lru_cache
# Import time for measuring execution
2import time
3
# Apply LRU cache with max 128 entries
4@lru_cache(maxsize=128)
# Define recursive Fibonacci function
5def fibonacci(n):
# Base case: return n for 0 or 1
6 if n < 2:
# Return the base value
7 return n
# Recursive case: sum of two previous numbers
8 return fibonacci(n - 1) + fibonacci(n - 2)
9
# Record start time
10start = time.time()
# Calculate fibonacci(35) - cached calls are instant
11result = fibonacci(35)
# Record end time
12end = time.time()
13
# Print the result
14print(f"fib(35) = {result}")
# Print execution time
15print(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

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

More Python examples at level 5

← Python typing practice