Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding multiple (not nested) if statements in my code

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 :)

like image 919
Hilla Shahrabani Avatar asked Jun 02 '26 19:06

Hilla Shahrabani


2 Answers

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)
like image 141
Hoog Avatar answered Jun 04 '26 09:06

Hoog


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
like image 39
Guimoute Avatar answered Jun 04 '26 09:06

Guimoute



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!