|
16 | 16 | fib_binet runtime: 0.0174 ms
|
17 | 17 | """
|
18 | 18 |
|
| 19 | +from functools import lru_cache |
19 | 20 | from math import sqrt
|
20 | 21 | from time import time
|
21 | 22 |
|
@@ -92,6 +93,39 @@ def fib_recursive_term(i: int) -> int:
|
92 | 93 | return [fib_recursive_term(i) for i in range(n + 1)]
|
93 | 94 |
|
94 | 95 |
|
| 96 | +def fib_recursive_cached(n: int) -> list[int]: |
| 97 | + """ |
| 98 | + Calculates the first n (0-indexed) Fibonacci numbers using recursion |
| 99 | + >>> fib_iterative(0) |
| 100 | + [0] |
| 101 | + >>> fib_iterative(1) |
| 102 | + [0, 1] |
| 103 | + >>> fib_iterative(5) |
| 104 | + [0, 1, 1, 2, 3, 5] |
| 105 | + >>> fib_iterative(10) |
| 106 | + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] |
| 107 | + >>> fib_iterative(-1) |
| 108 | + Traceback (most recent call last): |
| 109 | + ... |
| 110 | + Exception: n is negative |
| 111 | + """ |
| 112 | + |
| 113 | + @lru_cache(maxsize=None) |
| 114 | + def fib_recursive_term(i: int) -> int: |
| 115 | + """ |
| 116 | + Calculates the i-th (0-indexed) Fibonacci number using recursion |
| 117 | + """ |
| 118 | + if i < 0: |
| 119 | + raise Exception("n is negative") |
| 120 | + if i < 2: |
| 121 | + return i |
| 122 | + return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) |
| 123 | + |
| 124 | + if n < 0: |
| 125 | + raise Exception("n is negative") |
| 126 | + return [fib_recursive_term(i) for i in range(n + 1)] |
| 127 | + |
| 128 | + |
95 | 129 | def fib_memoization(n: int) -> list[int]:
|
96 | 130 | """
|
97 | 131 | Calculates the first n (0-indexed) Fibonacci numbers using memoization
|
@@ -163,8 +197,9 @@ def fib_binet(n: int) -> list[int]:
|
163 | 197 |
|
164 | 198 |
|
165 | 199 | if __name__ == "__main__":
|
166 |
| - num = 20 |
| 200 | + num = 30 |
167 | 201 | time_func(fib_iterative, num)
|
168 |
| - time_func(fib_recursive, num) |
| 202 | + time_func(fib_recursive, num) # Around 3s runtime |
| 203 | + time_func(fib_recursive_cached, num) # Around 0ms runtime |
169 | 204 | time_func(fib_memoization, num)
|
170 | 205 | time_func(fib_binet, num)
|
0 commit comments