Grouping memoized solutions in a dictionary

75 views Asked by At

I've got a function that I call thousands of times. It distinguishes between about 40 different cases based on the values of about 25 variables. Each variable has between 2 and 10 possible values. Since there aren't very many possibilities for each value, and only 40 cases I'm interested in, I was thinking of making each answer an integer between 0 and 9, and combining these integers similar to bitwise operators. Once combined, they could be used as the keys to a dictionary to retrieve the types I'm looking for. Does anybody know of an existing implementation of this solution, what it is called, or where I can read more about it? I'm trying to solve this in C++ or Python. The motivation here is to avoid having tons of logic statements obscuring the code. Also, since each variable is fully independent, using just if/else and/or switch statements I end up having to check each variable for each possible value several times since not all the different types group neatly into categories that share most of their logic. So this solution could make the code easier to read, and more efficient. Here's a Python example of the sort of thing I'm trying to do:

type_dict = {111: 'Type 1',
             112: 'Type 2',
             113: 'Type 3',
             # ...
             537: 'Type 32'} # etc.


answers = []
for each_run in list_of_scenarios:
    # Based on a bunch of logic, determine the value of each variable
    var_a = 5
    var_b = 3
    var_c = 7

    # Combine these variables to one key
    this_key = 100*var_a + 10*var_b + var_c

    answers.append(type_dict[this_key])
1

There are 1 answers

1
Mike Müller On BEST ANSWER

In Python, you can take advantage of the fact that tuples are valid dictionary keys:

type_dict = {(1, 1, 1): 'Type 1',
             (1, 1, 2): 'Type 2',
             (1, 1, 3): 'Type 3',
             (5, 3, 7): 'Type 32'}

var_a = 5
var_b = 3
var_c = 7

type_dict[(var_a, var_b, var_c)]

Returns:

'Type 32'