Let's say I'm trying to print out the orientation of a tablet device using its accelerometer that provides acceleration measurements in the horizontal and vertical directions of the display of the device. I know that such a printout could be done using a set of if
statements in a form such as the following:
if abs(stableAcceleration[0]) > abs(stableAcceleration[1]) and stableAcceleration[0] > 0:
print("right")
elif abs(stableAcceleration[0]) > abs(stableAcceleration[1]) and stableAcceleration[0] < 0:
print("left")
elif abs(stableAcceleration[0]) < abs(stableAcceleration[1]) and stableAcceleration[1] > 0:
print("inverted")
elif abs(stableAcceleration[0]) < abs(stableAcceleration[1]) and stableAcceleration[1] < 0:
print("normal")
Would it be possible to codify the logic of this in some neater form? Could a sort of truth table be constructed such that the orientation is simply a lookup value of this table? What would be a good way to do something like this?
EDIT: Following a suggestion by @jonrsharpe, I have implemented the logic in a way like the following:
tableOrientations = {
(True, True): "right",
(True, False): "left",
(False, True): "inverted",
(False, False): "normal"
}
print(
tableOrientations[(
abs(stableAcceleration[0]) > abs(stableAcceleration[1]),
stableAcceleration[0] > 0
)]
)
Consider doing something along the lines of this:
x = 0;
if abs(stableAcceleration[0]) > abs(stableAcceleration[1]) :
x += 2
if stableAcceleration[0] > 0:
x +=1
list = ["normal", "invert", "left", "right"]
print(list[x])
That being said, your series of if
statements don't cover every case.