Skip to content

Commit 63164d9

Browse files
committed
Minor changes
1 parent 861327d commit 63164d9

File tree

1 file changed

+26
-17
lines changed

1 file changed

+26
-17
lines changed

maths/fibonacci.py

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,20 @@
44
and a simplified form of Binet's formula
55
66
NOTE 1: the iterative, recursive, memoization functions are more accurate than
7-
the Binet's formula function because the iterative function doesn't use floats
7+
the Binet's formula function because the Binet formula function uses floats
88
99
NOTE 2: the Binet's formula function is much more limited in the size of inputs
1010
that it can handle due to the size limitations of Python floats
11+
12+
RESULTS: (n = 20)
13+
fib_iterative runtime: 0.0055 ms
14+
fib_recursive runtime: 6.5627 ms
15+
fib_memoization runtime: 0.0107 ms
16+
fib_binet runtime: 0.0174 ms
1117
"""
1218

1319
from math import sqrt
1420
from time import time
15-
from typing import Callable
1621

1722

1823
def time_func(func, *args, **kwargs):
@@ -87,33 +92,37 @@ def fib_recursive_term(i: int) -> int:
8792
return [fib_recursive_term(i) for i in range(n + 1)]
8893

8994

90-
def fib_memoization() -> Callable[[int], int]:
95+
def fib_memoization(n: int) -> list[int]:
9196
"""
92-
Calculates the nth fibonacci number using Memoization
93-
>>> fib_memoization()(5)
94-
5
95-
>>> fib_memoization()(100)
96-
354224848179261915075
97-
>>> fib_memoization()(25)
98-
75025
99-
>>> fib_memoization()(40)
100-
102334155
97+
Calculates the first n (0-indexed) Fibonacci numbers using memoization
98+
>>> fib_memoization(0)
99+
[0]
100+
>>> fib_memoization(1)
101+
[0, 1]
102+
>>> fib_memoization(5)
103+
[0, 1, 1, 2, 3, 5]
104+
>>> fib_memoization(10)
105+
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
106+
>>> fib_iterative(-1)
107+
Traceback (most recent call last):
108+
...
109+
Exception: n is negative
101110
"""
111+
if n < 0:
112+
raise Exception("n is negative")
102113
# Cache must be outside recursuive function
103114
# other it will reset every time it calls itself.
104-
cache: dict[int, int] = {1: 1, 2: 1} # Prefilled cache
115+
cache: dict[int, int] = {0: 0, 1: 1, 2: 1} # Prefilled cache
105116

106117
def rec_fn_memoized(num: int) -> int:
107-
if num < 1:
108-
raise Exception("n is negative")
109118
if num in cache:
110119
return cache[num]
111120

112121
value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2)
113122
cache[num] = value
114123
return value
115124

116-
return rec_fn_memoized
125+
return [rec_fn_memoized(i) for i in range(n + 1)]
117126

118127

119128
def fib_binet(n: int) -> list[int]:
@@ -157,5 +166,5 @@ def fib_binet(n: int) -> list[int]:
157166
num = 20
158167
time_func(fib_iterative, num)
159168
time_func(fib_recursive, num)
160-
time_func(fib_memoization(), num)
169+
time_func(fib_memoization, num)
161170
time_func(fib_binet, num)

0 commit comments

Comments
 (0)