I am writing a function to scan a specific map (2D array). In order to avoid scanning spots outside of the array, I wrote a few if statements, but it feels like the wrong, long, inefficient way of doing it.
H is the map's height value, int W is for width, int c is the current spot, a tuple containing x and y values.
floorH = c[0]-D
floorW = c[1]-D
ceilingH = c[0]+D+1
ceilingW = c[1]+D+1
if floorH < 0:
floorH = 0
if floorW < 0:
floorW = 0
if ceilingH > H:
ceilingH = H
if ceilingW > W:
ceilingW = W
How can I write this better?
Thanks in advance :)
asked Feb 12, 2019 at 17:06
Hilla Shahrabani
1251 gold badge2 silver badges10 bronze badges
2 Answers 2
Instead of using conditionals you could just use the max and min functions.
floorH = c[0]-D
floorW = c[1]-D
ceilingH = c[0]+D+1
ceilingW = c[1]+D+1
floorH = max(floorH, 0)
floorW = max(floorW, 0)
ceilingH = min(ceilingH , H)
ceilingW = min(ceilingW , W)
Actually you can make it even shorter:
floorH = max(c[0]-D, 0)
floorW = max(c[1]-D, 0)
ceilingH = min(c[0]+D+1, H)
ceilingW = min(c[1]+D+1, W)
answered Feb 12, 2019 at 17:11
Hoog
2,2981 gold badge15 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Prune
This is the one I use. My teammates and I find it easier to read and less prone to boundary errors.
Hilla Shahrabani
This is exactly what I was looking for. Thank you!
You can format your if like this to save space:
floorH = c[0]-D if c[0]-D > 0 else 0
floorW = c[1]-D if c[1]-D > 0 else 0
ceilingH = c[0]+D+1 if c[0]+D+1 < H else H
ceilingW = c[1]+D+1 if c[1]+D+1 < W else W
answered Feb 12, 2019 at 17:14
Guimoute
4,6743 gold badges17 silver badges34 bronze badges
Comments
lang-py