I am working on the classic making change with coins problem with Python. This is my implementation.
def memo(fn):
def helper(*args): # here, * indicate the fn take arbitrary number of argumetns
d = {}
if args in d:
return d[args] # args is a tuple, immutable, hashable
else:
res = fn(*args) # here * expand a tuple as arguments
d[args] = res
return res
return helper
@memo
def change(options, n):
if n < 0 or options ==():
return 0
elif n == 0:
return 1
else:
return change(options, n- options[0]) + change(options[1:], n)
And it turns out, the memoized version is even slower than original version! Why? What is going wrong in my implementation?
This is without memoization:
In [172]: %timeit change((50, 25, 10, 5, 1), 100)
100 loops, best of 3: 7.12 ms per loop
This is with memoization:
In [170]: %timeit change((50, 25, 10, 5, 1), 100)
10 loops, best of 3: 21.2 ms per loop