-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfib_puramente_iterativo_memoization.py
72 lines (55 loc) · 1.7 KB
/
fib_puramente_iterativo_memoization.py
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
66
67
68
69
70
71
72
import Memoria as memo
class IterativoMemorization():
def __init__(self):
LIMITE = 4000000
TAXA_LIMPEZA = 0.7
self.memoria = memo.Cerebro(LIMITE, TAXA_LIMPEZA)
def calcular(self, n):
valor_final = 0
for i in range(2, n+1):
str_n1 = str(i-1)
str_n2 = str(i-2)
str_n3 = str((i-1)+(i-2))
n_1 = self.memoria.get_lembranca(str_n1)
n_2 = self.memoria.get_lembranca(str_n2)
if (n_1 == -1 and (i-1) > 1):
n_1 = self.calc_fib(i-1)
#print("fib({})={}".format(str_n1, n_1))
self.memoria.nova_memoria(str_n1, n_1)
elif (n_2 == -1 and (i-2) > 1):
n_2 = self.calc_fib(i-2)
self.memoria.nova_memoria(str_n2, n_2)
if( i > 3):
n_3 = n_1 + n_2
#print ("FIB({}) :: fib({})={} + fib({})={} = {}".format(str_n3, (i-1), n_1, (i-2), n_2, n_3))
self.memoria.nova_memoria(i, n_3)
valor_final = n_3
return valor_final
def calc_fib(self, n):
if n == 0: return 0
if n == 1: return 1
str_n1 = str(n-1)
str_n2 = str(n-2)
n_1 = self.memoria.get_lembranca(str_n1)
n_2 = self.memoria.get_lembranca(str_n2)
if (n_1 == -1):
n_1 = self.calc_fib_it(n-1)
self.memoria.nova_memoria(str_n1, n_1)
if (n_2 == -1):
n_2 = self.calc_fib_it(n-2)
self.memoria.nova_memoria(str_n2, n_2)
return n_1 + n_2
def calc_fib_it(self, n):
if (n <= 2):
return 1
fib1 = 1
fib2 = 1
for i in range(2, n+1):
fib3 = fib1 + fib2
fib1 = fib2
fib2 = fib3
return fib1
def get_funcao_calc(self):
return lambda n: self.calcular(n)
def __str__(self):
return "Iterativo puro + Memoization"