Repository navigation
Expand file tree
/
Copy pathlabor.py
More file actions
61 lines (46 loc) · 1.38 KB
/
Copy pathlabor.py
File metadata and controls
61 lines (46 loc) · 1.38 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
import timeit
"""
A stock of varying computational-intensive functions.
"""
def recursive_fib(n):
if n == 0 or n == 1:
return n
else:
return recursive_fib(n-1) + recursive_fib(n-2)
def memoize(f):
cache = {}
def decorated_function(arg):
if arg in cache:
return cache[arg]
else:
cache[arg] = f(arg)
return cache[arg]
return decorated_function
@memoize
def recursive_fib_cached(n):
if n == 0 or n == 1:
return n
else:
return recursive_fib_cached(n-1) + recursive_fib_cached(n-2)
def iterative_fib(n):
a, b = 0, 1
for i in xrange(n):
a, b = b, a + b
return a
def demonstrate_load(n):
print "* Running 3 variants of fibonacci, set to calculate the {}th fibonacci number...".format(
n
)
test_scenarios = [
('naive recursive implementation', recursive_fib),
('recursive implementation with a cache', recursive_fib_cached),
('iterative implementation', iterative_fib)
]
for test_description, fib_test in test_scenarios:
print "#" * 20
print "Running {} ...".format(test_description)
start_time = timeit.default_timer()
fib_test(n)
end_time = timeit.default_timer()
print "{} took {} seconds to complete".format(test_description, end_time-start_time)
# demonstrate_load(37)