Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4d3fc9d

Browse files
committed
FEAT Implemented fibonacci sequence algorithm utilizing dynamic and programming memoization
1 parent dd1c362 commit 4d3fc9d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

‎main.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,20 @@ def fib(n: int) -> int:
2727

2828
return Fibonacci.fib(n - 2) + Fibonacci.fib(n - 1)
2929

30+
@staticmethod
31+
def fast_fib(n: int, cache: {int: int}) -> int:
32+
"""Fibonacci sequence algorithm utilizing dynamic programing and memoization"""
33+
if n == 0:
34+
cache[n] = 0
35+
return 0
36+
37+
if n == 1:
38+
cache[n] = 1
39+
return 1
40+
41+
cache[n] = cache[n - 2] + cache[n - 1]
42+
return cache[n]
43+
3044

3145
# ---------------------------------------------------------------------------------------------------------
3246

@@ -135,6 +149,8 @@ def main():
135149

136150
test_int_matrix = [[0] * 2 for _ in range(3)]
137151

152+
cache = {}
153+
138154
for i in range(3):
139155
for j in range(2):
140156
test_int_matrix[i][j] = generator.randint(0, 9)
@@ -163,6 +179,12 @@ def main():
163179
print()
164180
print(f"floor of lg(128): { lg(128) }")
165181

182+
print()
183+
print("- Dynamic Programming and Memoization Fib")
184+
185+
for i in range(40):
186+
print(Fibonacci.fast_fib(i, cache))
187+
166188
print()
167189
print("- Recursive Fib")
168190

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /