Skip to content

Commit a9667c0

Browse files
committed
refactored and added new solution
1 parent 20e1d45 commit a9667c0

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

fib_numbers.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,33 @@
77
F(0) = 0, F(1) = 1
88
F(n) = F(n - 1) + F(n - 2), for n > 1. """
99

10+
# importing lru_cache function for memoization
11+
from functools import lru_cache
1012
# Solution
11-
def fibonacci(n):
13+
@lru_cache(maxsize=None)
14+
def fibonacci(n: int) -> int:
1215
if n <= 0:
1316
return 0
1417
elif n == 1:
1518
return 1
1619
return fibonacci(n-1) + fibonacci(n-2) # recursive case
1720

1821
# Check
19-
print(fibonacci(5)) # Output -> 5
22+
print(fibonacci(42)) # Output -> 267914296
2023
print(fibonacci(12)) # Output -> 144
2124
print(fibonacci(-11)) # Output -> 0
25+
print(fibonacci(6)) # Output -> 8
26+
27+
# Solution 2 from LinkednIn folowers
28+
def fibonacci2(n):
29+
i = 0
30+
previous, current = 0, 1
31+
while i < n:
32+
previous, current = current, previous + current
33+
i += 1
34+
return previous
35+
36+
print(fibonacci2(42))
37+
print(fibonacci2(12)) # Output -> 144
38+
print(fibonacci2(-11)) # Output -> 0
39+
print(fibonacci2(6)) # Output -> 8

0 commit comments

Comments
 (0)