-
Notifications
You must be signed in to change notification settings - Fork 0
/
fib_example.py
39 lines (35 loc) · 1.17 KB
/
fib_example.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
import time
from math import sqrt
from interchangeable import interchangeable
def fib_recursive(n):
if n == 0 or n == 1:
return 1
return fib_recursive(n-1) + fib_recursive(n-2)
def fib_dynamic(n):
arr = [0,1]
while len(arr) < n + 1:
arr.append(arr[-1] + arr[-2])
return arr[n]
def fib_closed_form(n):
return int(round(1/(sqrt(5))*((1+sqrt(5))/2)**n - (1/(sqrt(5))*((1-sqrt(5))/2)**n)))
if __name__ == "__main__":
fib = interchangeable(fib_closed_form, fib_dynamic)
start = time.time()
fib.learning = True
for i in range(350):
print fib(i)
print "took ", time.time() - start, " seconds"
fib.learning = False
start = time.time()
for i in range(350):
print fib(i)
choosing_time = time.time() - start
print "choosing took ", choosing_time, " seconds"
start = time.time()
for i in range(350):
fib_dynamic(i)
print "fib_dyanmic took ", (time.time() - start) - choosing_time, " more seconds than choosing"
start = time.time()
for i in range(350):
fib_closed_form(i)
print "closed took ", (time.time() - start) - choosing_time, " more seconds than choosing"