LozCodes
LozCodes

Reputation: 119

How can I avoid having lots of if statements when finding combinations of radio buttons?

I have a database that looks like this:

Rat Age RA RB RAB RC RD RCD
A 1 None None Mild Severe None Death
B 2 Mild Severe Severe None Mild Severe

RA stands for reaction to substance A, RB reaction to substance B, RAB reaction to substances A and B at the same time etc - there are more than A-D substances but for time I haven't listed them here

I'm developing a GUI that will allow the user to select a rat from a list of radio buttons, then choose any number and combination of substances (e.g. A, B, C, E or A, D, F) and I want to display the reaction the selected rat has to the selected substances.

At the moment I've got an if statement for every single possible combination of substance, which is getting a bit silly. I did think about a switch statement but this would also be very long. There's no particular logic to what combination of substances cause which reaction in each rat. Is there a better way of doing this?

Upvotes: 0

Views: 73

Answers (1)

Byte Ninja
Byte Ninja

Reputation: 911

If you can map the combinations of substances to the reactions for each rat in a dictionary like this:

    reactions = {
        'A': {
            ('A',): 'None',
            ('B',): 'None',
            ('A', 'B'): 'Mild',
            ('C',): 'Severe',
            ('D',): 'Death',
            ('C', 'D'): 'Severe'
            # ...
        },
        'B': {
            ('A',): 'Mild',
            ('B',): 'Severe',
            ('A', 'B'): 'Severe',
            ('C',): 'None',
            ('D',): 'Mild',
            ('C', 'D'): 'Severe'
            # ...
        }
        # other rats
    }

Then

reaction = reactions[selected_rat].get(tuple(selected_substances), 'None')

will give you the reaction for the selected rat and substances from the GUI where selected_rat is of type str, and selected_substances is of type list containing str elements.

Upvotes: 0

Related Questions