28 lines
718 B
Python
28 lines
718 B
Python
#!/usr/bin/env python3
|
|
"""Fibonacci calculator with memoization.
|
|
|
|
Verifiable: f(10) = 55, f(20) = 6765
|
|
"""
|
|
from functools import lru_cache
|
|
|
|
|
|
@lru_cache(maxsize=None)
|
|
def fib(n: int) -> int:
|
|
"""Return the nth Fibonacci number (0-indexed)."""
|
|
if n < 0:
|
|
raise ValueError("n must be non-negative")
|
|
if n <= 1:
|
|
return n
|
|
return fib(n - 1) + fib(n - 2)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Test cases
|
|
assert fib(0) == 0, "fib(0) should be 0"
|
|
assert fib(1) == 1, "fib(1) should be 1"
|
|
assert fib(10) == 55, "fib(10) should be 55"
|
|
assert fib(20) == 6765, "fib(20) should be 6765"
|
|
|
|
print("All tests passed!")
|
|
print(f"fib(10) = {fib(10)}")
|
|
print(f"fib(20) = {fib(20)}") |