-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemoized_fibonacci.py
More file actions
66 lines (48 loc) · 2.17 KB
/
memoized_fibonacci.py
File metadata and controls
66 lines (48 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
link: https://www.codewars.com/kata/529adbf7533b761c560004e5
Problem Context
The Fibonacci sequence is traditionally used to explain tree recursion.
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
This algorithm serves welll its educative purpose but it's tremendously inefficient,
not only because of recursion, but because we invoke the fibonacci function twice,
and the right branch of recursion (i.e. fibonacci(n-2)) recalculates
all the Fibonacci numbers already calculated by the left branch (i.e. fibonacci(n-1)).
This algorithm is so inefficient that the time to calculate any Fibonacci number over 50 is simply too much.
You may go for a cup of coffee or go take a nap while you wait for the answer.
But if you try it here in Code Wars you will most likely get a code timeout before any answers.
For this particular Kata we want to implement the memoization solution.
This will be cool because it will let us keep using the tree recursion algorithm
while still keeping it sufficiently optimized to get an answer very rapidly.
The trick of the memoized version is that we will keep a cache data structure (most likely an associative array)
where we will store the Fibonacci numbers as we calculate them.
When a Fibonacci number is calculated, we first look it up in the cache,
if it's not there, we calculate it and put it in the cache, otherwise we returned the cached number.
Refactor the function into a recursive Fibonacci function
that using a memoized data structure avoids the deficiencies of tree recursion.
Can you make it so the memoization cache is private to this function?
"""
def memorise(function):
memory_list = [0, 1]
def wrapper(*args):
n = args[0]
if n < len(memory_list):
return memory_list[n]
else:
new_val = function(*args)
memory_list.append(new_val)
return new_val
return wrapper
@memorise
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def main():
print(fibonacci(50))
print(fibonacci(60))
print(fibonacci(70))
if __name__ == "__main__":
main()