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 functools
1from functools import lru_cache
2
# Apply LRU cache decorator with max 128 entries
3@lru_cache(maxsize=128)
# Define recursive fibonacci function
4def fibonacci(n):
# Base case: return n for 0 or 1
5 if n < 2:
# Return n directly
6 return n
# Recursive case: sum of two previous fibonacci numbers
7 return fibonacci(n - 1) + fibonacci(n - 2)
8
# Print first 10 fibonacci numbers
9for i in range(10):
# Print each number followed by space
10 print(fibonacci(i), end=" ")
# Print newline
11print()
# Print cache statistics
12print(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

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

More Python examples at level 5

← Python typing practice