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_cache2 # @lru_cache stores results of function calls# maxsize=None means unlimited cache size3@lru_cache(maxsize=None)4def fib(n): # Base case: fib(0)=0, fib(1)=15 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 comprehension9result = [fib(i) for i in range(10)]# Print the sequence10print(result)Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
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