Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I refactor this code snippet to make it more efficient?

I’m trying to make a matrix of actions based off game theory. So if two people meet, they can either both share, or one steal, or both steal, etc.

The outline of what I have looks like this (not the whole matrix, just so you get an idea):

if first_agent.type == "AlwaysShare" and second_agent.type == "AlwaysShare":
    pass
elif first_agent.type == "AlwaysSteal" and second_agent.type == "AlwaysShare":
    pass
elif first_agent.type == "AlwaysShare" and second_agent.type == "AlwaysSteal":
    pass

Clearly this is very inefficient and prone to mistakes. How can I optimise this so I can efficiently manage interactions for the matrix?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When I have a situation with multiple options, I like to make a dictionary of functions that handle the different possibilities. The keys are the encoded and normalized inputs. In your case, you can generate a key like this:

def key(first_agent, second_agent):
    key = [first_agent.type, second_agent.type]
    key.sort()
    return tuple(key)

Then your dictionary would look something like this:

def handle_share():
    pass

def handle_one_steal():
    pass

def handle_both_steal():
    pass

# Etc.

action_map = {
    ('AlwaysShare', 'AlwaysShare'): handle_share,
    ('AlwaysShare', 'AlwaysSteal'): handle_one_steal,
    ('AlwaysSteal', 'AlwaysSteal'): handle_both_steal,
}

If you scope the functions carefully (e.g., make them methods or nested functions as necessary), you can fine-tune any side effects you may need them to have.

Now you can replace your if-block with something like:

action_map[key(first_agent, second_agent)]()

Use action_map.get instead if you have a suitable default or no-op in mind, and don’t want to get KeyError for potentially unknown interactions.

The nice thing about doing it this way is that you can easily add new interactions: just implement a function and register it in the dictionary. Want to have a third agent? Make key accept *args instead of a fixed number of agents. Need to define another type of agent? No problem. And so on.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading