To implement a Python function that calculates the Fibonacci numbers with amortized constant runtime and linear memory, we can use memoization with a default argument as a list. This approach ensures that once a Fibonacci number is computed, it is stored for future reference, leading to O(1) access time for previously computed values.
However, the key challenge is to express this logic in one line, which requires a clever use of Python's features such as list comprehensions, the or operator, and side effects.
✅ One-Liner Implementation
def fib(n, m=[0,1]): return m[n] if n < len(m) else ([m.append(m[-1]+m[-2]) for _ in range(n - len(m) + 1)] or m[n])
🔍 Explanation
m = [0, 1]: This is a mutable default argument that persists across function calls, acting as a memoization cache.
m[n] if n < len(m): If the requested index n is already in the list, return it directly — O(1) time.
[m.append(m[-1]+m[-2]) for _ in range(...)]:
- This list comprehension executes a loop that appends the next Fibonacci number to the list.
- Each
m.append(...) is a side effect, not a value, so the list comprehension returns a list of Nones.
or m[n]: Since the list comprehension returns None, the or operator falls back to m[n], which is now available after the loop.
🧠 Why This Works
- Amortized Constant Runtime: The first call to a new
n will compute all Fibonacci numbers up to n, which is O(n) time. Subsequent calls for smaller n are O(1), so the average time per call is O(1).
- Linear Memory: The memo list grows at most linearly with the maximum
n requested.
- One Line: All logic is packed into a single
return statement, leveraging Python’s expressive syntax.
📌 Example Usage
print(fib(0)) # 0
print(fib(1)) # 1
print(fib(2)) # 1
print(fib(5)) # 5
print(fib(10)) # 55
Each call after the first will benefit from the memoized values, achieving amortized constant performance.