File tree Expand file tree Collapse file tree 1 file changed +20
-2
lines changed Expand file tree Collapse file tree 1 file changed +20
-2
lines changed Original file line number Diff line number Diff line change 7
7
F(0) = 0, F(1) = 1
8
8
F(n) = F(n - 1) + F(n - 2), for n > 1. """
9
9
10
+ # importing lru_cache function for memoization
11
+ from functools import lru_cache
10
12
# Solution
11
- def fibonacci (n ):
13
+ @lru_cache (maxsize = None )
14
+ def fibonacci (n : int ) -> int :
12
15
if n <= 0 :
13
16
return 0
14
17
elif n == 1 :
15
18
return 1
16
19
return fibonacci (n - 1 ) + fibonacci (n - 2 ) # recursive case
17
20
18
21
# Check
19
- print (fibonacci (5 )) # Output -> 5
22
+ print (fibonacci (42 )) # Output -> 267914296
20
23
print (fibonacci (12 )) # Output -> 144
21
24
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
You can’t perform that action at this time.
0 commit comments