Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to write these ifs nicer?

I need to write these four ifs 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?

like image 429
manuel Avatar asked Feb 01 '12 23:02

manuel


2 Answers

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...

like image 20
kindall Avatar answered Sep 22 '22 17:09

kindall


dx, dy = -dy, dx 

When in doubt, apply maths. ;)

like image 60
Magnus Hoff Avatar answered Sep 18 '22 17:09

Magnus Hoff