-
Notifications
You must be signed in to change notification settings - Fork 0
/
L19Q7_Memoization.py
61 lines (52 loc) · 2.18 KB
/
L19Q7_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
# [Double Gold Star] Memoization is a way to make code run faster by saving
# previously computed results. Instead of needing to recompute the value of an
# expression, a memoized computation first looks for the value in a cache of
# pre-computed values.
# Define a procedure, cached_execution(cache, proc, proc_input), that takes in
# three inputs: a cache, which is a Dictionary that maps inputs to proc to
# their previously computed values, a procedure, proc, which can be called by
# just writing proc(proc_input), and proc_input which is the input to proc.
# Your procedure should return the value of the proc with input proc_input,
# but should only evaluate it if it has not been previously called.
'''
#this would be a better data structure to run multiple functions
cache: { proc1': {'proc_input1: 1,
proc_input2: 3},
'proc2: {'proc_input2: 3, proc_input3: 4},
},
'''
def cached_execution(cache, proc, proc_input):
if proc_input not in cache:
cache[proc_input] = proc(proc_input)
return cache[proc_input]
def factorial(n):
print "Running factorial"
result = 1
for i in range(2, n + 1):
result = result * i
return result
'''
cache = {} # start cache as an empty dictionary
### first execution (should print out Running factorial and the result)
print cached_execution(cache, factorial, 50)
print "Second time:"
### second execution (should only print out the result)
print cached_execution(cache, factorial, 50)
print "Third time:"
### third execution (should add the result of 30 to the key)
print cached_execution(cache, factorial, 30)
'''
# Here is a more interesting example using cached_execution
# (do not worry if you do not understand this, though,
# it will be clearer after Unit 6):
def cached_fibo(n):
if n == 1 or n == 0:
return n
else:
return (cached_execution(cache, cached_fibo, n - 1 )
+ cached_execution(cache, cached_fibo, n - 2 ))
cache = {} # new cache for this procedure
# do not try this at home...at least without a cache!
print cached_execution(cache, cached_fibo,20)
print cached_execution(cache, cached_fibo,20)
print cached_execution(cache, cached_fibo,100)