I need to write these four if
s in Python. Notice what it does, is changing between four possible states in a loop: 1,0 -> 0,1 -> -1,0 -> 0,-1
and back to first.
if [dx, dy] == [1,0]: dx, dy = 0, 1 if [dx, dy] == 0, 1: dx, dy = -1, 0 if [dx, dy] == [-1, 0] dx, dy = 0, -1 if [dx, dy] == [0, -1]: dx, dy = 1, 0
Can anyone suggest me a better/nicer way to write this?
Magnus' suggestion is undeniably the right answer to your question as posed, but generally speaking, you want to use a dictionary for problems like this:
statemap = {(1, 0): (0, 1), (0, 1): (-1, 0), (-1, 0): (0, -1), (0, -1): (1, 0)} dx, dy = statemap[dx, dy]
Even in this case I could argue using a dictionary is better, since it's clear that there are exactly four states and that they repeat, but it's hard to resist the sheer beauty of all teh maths.
By the way, the code in your question has a bug in it, and, assuming that the values you test for are the only possible values, is equivalent to:
dx, dy = 1, 0
The bug is that you need elif
for the second and subsequent conditions, otherwise you're continuing to test dx
and dy
after changing them. If they're 1
and 0
, then all your conditions will be true and they end up the same at the end! If they start out as 0
and 1
then the second and all subsequent conditions will be true, and you again end up with 1, 0
. And so on...
dx, dy = -dy, dx
When in doubt, apply maths. ;)
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