How can I implement two memoization in one function?

78 views Asked by At

I wish to solve a problem with a recursive function using two memoization dictionaries, but I'm not sure how to execute this idea.

From what I have learned, when using just one memoization dicionary, the code structure looks similar. For example, to 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 I add to the code to use two memoization dicitionaries? What should I add to the def line, and in the recursive calls?

my problem:

list = [(16, 1, 4), (17, 2, 9), (3, 17, 10)]

which list [i][0] is the values. I should get the maximum possible combination values, considering two limiting factors given: list[i][1] and list[i][2].

1

There are 1 answers

0
Dan Oberlam On

I can't fathom why you would want to use two different dictionaries, but I'd use a 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 the two different dictionaries
myfunction(1, use_dict1=False)
myfunction(1)