python fib function one line amortized constant runtime linear memory
- User
python fib function one line amortized constant runtime linear memory
Assistant
Here's a Python one-liner for the Fibonacci sequence with amortized constant runtime and linear memory usage:
pythonfib = lambda n: (lambda f: f(n, [0,1]+[0]*(n-1)))(lambda n, memo: memo[n] if n<2 or memo[n] else (memo.__setitem__(n, f(n-1, memo)+f(n-2, memo)) or memo[n]))Explanation:
This uses memoization (dynamic programming) with a list to store computed values, achieving:
- Amortized O(1) runtime per call (after initial computation)
- O(n) memory (stores all values up to n)
How it works:
- The outer lambda takes and initializes a memoization list
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.