python - How can I implement two memoization in one function? -
i wish solve problem recursive function using 2 memoization dictionaries, i'm not sure how execute idea.
from have learned, when using 1 memoization dicionary, code structure looks similar. example, solve fibonacci number:
def fib_mem(n,mem=none): if n < 2: return n if mem == none: mem = {} if n not in mem: mem[n] = fib_mem(n-1,mem) + fib_mem(n-2,mem) return mem[n]
what should add code use 2 memoization dicitionaries? should add def
line, , in recursive calls?
my problem:
list = [(16, 1, 4), (17, 2, 9), (3, 17, 10)]
which list [i][0]
values. should maximum possible combination values, considering 2 limiting factors given: list[i][1]
, list[i][2]
.
i can't fathom why want use 2 different dictionaries, i'd use decorator
from functools import wraps def memoize_two_dict(func): dict1 = {} dict2 = {} @wraps(func) def wrapper(*args, use_dict1=true): targs = tuple(args) if use_dict1: if targs not in dict1: dict1[targs] = func(*args) return dict1[targs] else: if targs not in dict2: dict2[targs] = func(*args) return dict2[targs] return wrapper @memoize_two_dict def myfunction(args): ... # uses 2 different dictionaries myfunction(1, use_dict1=false) myfunction(1)
Comments
Post a Comment