Skip to content

Commit 4939e84

Browse files
Create cached fibonacci algorithm (TheAlgorithms#8084)
* feat: Add `fib_recursive_cached` func * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * doc: Show difference in time when caching algorithm Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 32a1ff9 commit 4939e84

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

Diff for: maths/fibonacci.py

+37-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
fib_binet runtime: 0.0174 ms
1717
"""
1818

19+
from functools import lru_cache
1920
from math import sqrt
2021
from time import time
2122

@@ -92,6 +93,39 @@ def fib_recursive_term(i: int) -> int:
9293
return [fib_recursive_term(i) for i in range(n + 1)]
9394

9495

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+
95129
def fib_memoization(n: int) -> list[int]:
96130
"""
97131
Calculates the first n (0-indexed) Fibonacci numbers using memoization
@@ -163,8 +197,9 @@ def fib_binet(n: int) -> list[int]:
163197

164198

165199
if __name__ == "__main__":
166-
num = 20
200+
num = 30
167201
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
169204
time_func(fib_memoization, num)
170205
time_func(fib_binet, num)

0 commit comments

Comments
 (0)