Hilla Shahrabani
Hilla Shahrabani

Reputation: 125

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

Upvotes: 3

Views: 138

Answers (2)

Guimoute
Guimoute

Reputation: 4629

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

Upvotes: 1

Hoog
Hoog

Reputation: 2298

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)

Upvotes: 8

Related Questions