Best way to combine a permutation of conditional statements
You can use a map of cases to results:
cases = { (True, True, True, True): "Case 1",
(True, True, True, False): "Case 2",
(True, True, False, True): "Case 3",
(True, True, False, False):"Case 4",
(True, False, True, True): "Case 5",
(True, False, True, False):"Case 6",
(True, False, False, True): "Case 7",
(True, False, False, False):"Case 8",
(False, True, True, True): "Case 9",
(False, True, True, False):"Case 10",
(False, True, False, True): "Case 11",
(False, True, False, False):"Case 12",
(False, False, True, True): "Case 13",
(False, False, True, False):"Case 14",
(False, False, False, True): "Case 15",
(False, False, False, False):"Case 16"}
print(cases[(x,y,z,t])
If you want to do something else/different for each case, you could add a function to that map.
cases = { (True, True, True, True): foo_func,
(True, True, True, False): bar_func,
...}
result = cases[(x,y,x,t)](*args)
You can also use one of the masking solutions to make the code shorter, or if you have too many cases to write out, but for smaller sets of cases, this explicit representation will be clearer and easier to maintain.
you could get your case number directly from binary manipulation of your booleans:
case = (x^1) << 3 | (y^1) << 2 | (z^1) << 1 | (t^1) + 1
print(f'Case {case}')
if you look at John Kugelman's answer you see that x, y, z, t
are just the 'bits' of your case number (where True=0
and False=1
)... so i construct an int
setting those bits (and then add 1
because you start counting at 1
).
if the numbering is arbitrary you can simplify that down to x << 3 | y << 2 | z << 1 | t
and take it from there.
this is easily extensible to a larger number of boolean variables.
then to do something based on the case number i suggest you create a dictionary containing the case
as key and the function or data or whatever as value. something like:
case_functions = {1: func_1, 2: func_2, ...}
res = case_functions(case)(some argument)