Second version of the custom cache function won't work if we have duplicate arguments.
amirsoroush opened this issue · 1 comments
amirsoroush commented
Hi Fred.
At the end of the file Part 3/Section 05 - Sets/06 - Frozen Sets.ipynb, we created a custom function for memoization replacing the lru_cache
.
The second version of it is:
We can even tweak this to effectively provide more efficient caching when the order of positional arguments is not important either:
def memoizer(fn):
cache = {}
def inner(*args, **kwargs):
key = frozenset(args) | frozenset(kwargs.items())
if key in cache:
return cache[key]
else:
result = fn(*args, **kwargs)
cache[key] = result
return result
return inner
@memoizer
def adder(*args):
print('calculating...')
return sum(args)
I just wanted to note that this cache mechanism won't work if we have duplicate arguments. That set (frozenset actually) removes the duplicate arguments.
Take a look at this example:
print(adder(1, 2, 2))
print(adder(1, 1, 2)) # 5 !!
You may add a note that arguments should be different for this to work.
Thanks.
fbaptiste commented
Good point!