Calculates the first n (0-indexed) Fibonacci numbers using memoization >>> fib_memoization(0) [0] >>> fib_memoization(1) [0, 1] >>> fib_memoization(5) [0, 1, 1, 2, 3, 5] >>> fib_memoization(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_memoization(-1)
(n: int)
| 166 | |
| 167 | |
| 168 | def fib_memoization(n: int) -> list[int]: |
| 169 | """ |
| 170 | Calculates the first n (0-indexed) Fibonacci numbers using memoization |
| 171 | >>> fib_memoization(0) |
| 172 | [0] |
| 173 | >>> fib_memoization(1) |
| 174 | [0, 1] |
| 175 | >>> fib_memoization(5) |
| 176 | [0, 1, 1, 2, 3, 5] |
| 177 | >>> fib_memoization(10) |
| 178 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] |
| 179 | >>> fib_memoization(-1) |
| 180 | Traceback (most recent call last): |
| 181 | ... |
| 182 | ValueError: n is negative |
| 183 | """ |
| 184 | if n < 0: |
| 185 | raise ValueError("n is negative") |
| 186 | # Cache must be outside recursive function |
| 187 | # other it will reset every time it calls itself. |
| 188 | cache: dict[int, int] = {0: 0, 1: 1, 2: 1} # Prefilled cache |
| 189 | |
| 190 | def rec_fn_memoized(num: int) -> int: |
| 191 | if num in cache: |
| 192 | return cache[num] |
| 193 | |
| 194 | value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2) |
| 195 | cache[num] = value |
| 196 | return value |
| 197 | |
| 198 | return [rec_fn_memoized(i) for i in range(n + 1)] |
| 199 | |
| 200 | |
| 201 | def fib_binet(n: int) -> list[int]: |
nothing calls this directly
no test coverage detected