I want to create a dictionary that stores the name of a mathematical function, the input (a single number) and the result.
The structure should be something like cache = {procedure: {input:result}}
i.e.
cache = {'factorial': {4:24, 10:3628800, 20:2432902008176640000},
'square': {2:4, 5:25, 10:100}
'sum': {3:6, 5:10, 7:14}}
def factorial(n):
#print "Running factorial"
result = 1
for i in range(2, n + 1):
result = result * i
return result
def square(n):
result = n ^ 2
return result
def sum(n):
result = n * 2
return result
I don’t want the cache dictionary to be pre-created in the sense that it may not know which mathematical functions it will store values for. I want to then create a function, named cached_execution, that will first check the cache if the function has been called for the input and if so return what is stored as the value for the input:result pair.
If not then compute the operation, store it in cache and return the value. If the function exists in the cache then another key/value pair should be created under it. If not then create a new entry for the function name and store the key/value of the input/result under it.
The structure of cached_execution is simple but what I can’t figure out is how to append to a dictionary. It seems append is not a method that is allowed for a dictionary structure. I have tried various things without success.
Appreciate the help.
You might also want to look at Memoize. There are a number of possible implementations, 3 of which are on the Python.org wiki. Even if you write your own version, it is helpful to see how others have attacked the problem.