|
|
|
|
|
by Jtsummers
334 days ago
|
|
Memoization is caching so that's a strange reason to fail someone. You cache based on the function call and its arguments. SOME_FUN = dict(base_cases)
def some_fun(a, b, c):
if (a,b,c) in SOME_FUN: return SOME_FUN[(a,b,c)]
result = some_fun(a - 1, b - 1, c) + some_fun(a, b, c-1) # or whatever the recursive calls would be
SOME_FUN[(a,b,c)] = result
return result
That's it. Some languages (Python, Lisp) make it easy to take the naive version and wrap it (Python decorators are useful here) so that you don't have to write that code above. That's what the @cache decorator in functools does for you. You can memoize the naive version without needing to actually write a specific memoized version. |
|