I’m doing a lot of coding these days involving XY coordinates, and there’s a handful of little annoyances. They’re no one’s fault, I just want to vent.
First, it’s natural to say “x and y”, and it’s natural to say “height and width”, but x corresponds to width, and y to height, so I often make mistakes that switch the two:
ht, wd = foox, fooy # This is wrong.
The same goes for loops over x and y. The natural order to visit the points in a grid is the raster order: finish a row, then go on to the next row. But that means having the first loop be over y rather than x:
for y in range(lowy, hiy):
for x in range(lowx, hix):
For this last, there’s a solution: create a generator that makes x,y pairs in a single loop:
def xyrange(startx, endx, starty, endy):
""" Generate the pairs (x, y) in a rectangle.
for y in range(starty, endy):
for x in range(startx, endx):
Then this function is the only place that needs the inside-out y x ugliness, and you can use a single loop everywhere else:
for x, y in xyrange(lowx, hix, lowy, hiy):
This has the advantage that you can break out of the loop cleanly when you find a point you are looking for. It has the disadvantage that you can’t do an action at the end of each row.
Update: Richard Schwartz noticed that I originally had said,
First, it’s natural to say “x and y”, and it’s natural to say “height and width”, but x corresponds to height, and y to width, so I often make mistakes that switch the two.
which makes that sentence itself an error of the sort it describes, making it an unintentionally self-referential sentence!