Recursive Fibonacci in Python

Level 5171 keystrokes

This calculates Fibonacci numbers using recursion with memoization. @lru_cache prevents redundant calculations for efficiency.

Python code

# Import lru_cache for memoization (caching results)
1from functools import lru_cache
2
# @lru_cache stores results of function calls
# maxsize=None means unlimited cache size
3@lru_cache(maxsize=None)
4def fib(n):
# Base case: fib(0)=0, fib(1)=1
5 if n < 2:
6 return n
# Recursive case: fib(n) = fib(n-1) + fib(n-2)
7 return fib(n - 1) + fib(n - 2)
8
# Generate first 10 Fibonacci numbers using list comprehension
9result = [fib(i) for i in range(10)]
# Print the sequence
10print(result)

Output

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
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.

  • (× 7
  • )× 7
  • _× 2
  • -× 2
  • :× 2
  • =× 2
  • [× 1
  • ]× 1
  • @× 1
  • +× 1

More Python examples at level 5

← Python typing practice