I am trying to find a clean solution to implement a basic decision matrix in python. I have 8 sensors that monitor an installation, and based on the state of these 8 sensors, I need to activate some relays.
My decision matrix looks like (S are sensors and R are R):
S1 S2 S3 S4 S5 S6 S7 S8 R1 R2 R3
0 1 0 0 1 1 0 1 0 0 1
1 0 1 0 0 1 1 0 1 1 1
0 1 1 1 0 0 0 1 0 1 0
...
Currently the only implementation that I see, is a suite a if/elif statements for each row of my descision matrix like:
if S1==0 and S2==1 and S3==0 and S4==0 and S5==1 and S6==1 and S7==0 and S8==1:
relay_state('R1', 0)
relay_state('R2', 0)
relay_state('R3', 1)
elif ...
This will definitely work, but I wonder if there is a cleaner way to implement this?
you can use a dictionary of tuple
matrix = {
(0,1,0,0,1,1,0,1):(0,0,1),
(1,0,1,0,0,1,1,0):(1,1,1),
(0,1,1,1,0,0,0,1):(0,1,0),
}
S1,S2,S3,S4,S5,S6,S7,S8 = 0,1,0,0,1,1,0,1
R1,R2,R3=matrix[S1,S2,S3,S4,S5,S6,S7,S8]
print (R1,R2,R3)
$python test.py
(0, 0, 1)
Use list and compare lists:
if sensors == [0,1,0,1, ....]:
Even more efficient notations - if your handlers are functions, you may use a dictionary
decision_matrix = { (0,1,1,... ): some_handler, ... }
...
decision_matrix[sensors]()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With