Best way to combine a permutation of conditional statements

2024/9/19 20:00:17

So, I have a series of actions to perform, based on 4 conditional variables - lets say x,y,z & t. Each of these variables have a possible True or False value. So, that is a total of 16 possible permutations. And I need to perform a different action for each permutation.

What is the best way to do this rather than making a huge if-else construct.

Lets see a simplified example. This is how my code would look if I try to contain all the different permutations into a large if-else construct.

if (x == True):if (y == True):if (z == True):if (t == True):print ("Case 1")else:print ("Case 2")else:if (t == True):print ("Case 3")else:print ("Case 4")else:if (z == True):if (t == True):print ("Case 5")else:print ("Case 6")else:if (t == True):print ("Case 7")else:print ("Case 8")
else:if (y == True):if (z == True):if (t == True):print ("Case 9")else:print ("Case 10")else:if (t == True):print ("Case 11")else:print ("Case 12")else:if (z == True):if (t == True):print ("Case 13")else:print ("Case 14")else:if (t == True):print ("Case 15")else:print ("Case 16")

Is there any way to simplify this? Obviously, my objective for each case is more complicated than just printing "Case 1".

Answer

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.

https://en.xdnf.cn/q/72473.html

Related Q&A

Fast way to get N Min or Max elements from a list in Python

I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like:f = lambda x: some_function_of(x, local_variabl…

Continue if else in inline for Python

I have not been able to find the trick to do a continue/pass on an if in a for, any ideas?. Please dont provide explicit loops as solutions, it should be everything in a one liner.I tested the code wi…

HTTPError: HTTP Error 403: Forbidden on Google Colab

I am trying to download MNIST data in PyTorch using the following code:train_loader = torch.utils.data.DataLoader(datasets.MNIST(data,train=True,download=True,transform=transforms.Compose([transforms.T…

Pandas partial melt or group melt

I have a DataFrame like this>>> df = pd.DataFrame([[1,1,2,3,4,5,6],[2,7,8,9,10,11,12]], columns=[id, ax,ay,az,bx,by,bz]) >>> dfid ax ay az bx by bz 0 1 1 2 3 4 5 6…

How do I detect when my window is minimized with wxPython?

I am writing a small wxPython utility.I would like to use some event to detect when a user minimizes the application/window.I have looked around but did not find an event like wx.EVT_MINIMIZE that I co…

Pandas: How to select a column in rolling window

I have a dataframe (with columns a, b, c) on which I am doing a rolling-window.I want to be able to filter the rolling window using one of the columns (say a) in the apply function like belowdf.rolling…

What is the fastest way in Cython to create a new array from an existing array and a variable

Suppose I have an arrayfrom array import array myarr = array(l, [1, 2, 3])and a variable: myvar = 4 what is the fastest way to create a new array:newarray = array(l, [1, 2, 3, 4])You can assume all ele…

Subclassing and built-in methods in Python

For convenience, I wanted to subclass socket to create an ICMP socket:class ICMPSocket(socket.socket):def __init__(self):socket.socket.__init__(self, socket.AF_INET,socket.SOCK_RAW,socket.getprotobynam…

How to load Rs .rdata files into Python?

I am trying to convert one part of R code in to Python. In this process I am facing some problems.I have a R code as shown below. Here I am saving my R output in .rdata format.nms <- names(mtcars) s…

how to set cookie in python mechanize

After sending request to the serverbr.open(http://xxxx)br.select_form(nr=0) br.form[MESSAGE] = 1 2 3 4 5br.submit()I get the response title, which has set-cookieSet-Cookie: PON=xxx.xxx.xxx.111; expir…