0

I have a program that runs on a 2D array. I'm checking certein indicies in this array to see what they are equal to:

if Board[current_y][current_x + 1] == "X" or current_x + 1 >= 5 or (current_y, current_x+1) in index_List or Board[current_y][current_x + 1] == "-":
        direction_list.remove("right")
if Board[current_y][current_x - 1] == "X" or current_x - 1 < 0 or (current_y, current_x-1) in index_List or Board[current_y][current_x - 1] == "-":
    direction_list.remove("left")
if current_y + 1 >= 5 or Board[current_y + 1][current_x] == "X" or (current_y+1, current_x) in index_List or Board[current_y + 1][current_x] == "-":
    direction_list.remove("down")
if current_y - 1 < 0 or Board[current_y - 1][current_x] == "X" or (current_y-1, current_x) in index_List or Board[current_y - 1][current_x] == "-":
    direction_list.remove("up")

This is something for a simple pathfinder I'm working on, where it checks one index to the right, left, up, or down and sees if the program can move to that index. However, when it reaches the edge, I'm checking if the value in an index that doesn't exist in the array is equal to "X".

Is there a way to make Python not throw an error in a case like this? I also program in C, and whenever you go out of bounds in C, it just makes it equal to NULL. Is there any way to make Python work like this?

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Punzicul
  • 51
  • 1
  • 5
  • 1
    Out of bounds accesses in C are [undefined behavior](https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why). Don't ever attempt to access an element that is out of bounds in C. – BrokenBenchmark Mar 15 '22 at 20:07
  • Not sure why this was closed as a duplicate; the issue has to do with short-circuit evaluation, _not_ ignoring exceptions. – BrokenBenchmark Mar 15 '22 at 20:11

2 Answers2

1

Your short-circuit evaluation is wrong. You're performing the bounds check after, rather than before, you attempt to access an array element. Suppressing out-of-index errors is not the best approach.

For the first if statement, this:

if Board[current_y][current_x + 1] == "X" or current_x + 1 >= 5 or ...

should be

if current_x + 1 >= 5 or Board[current_y][current_x + 1] == "X" or ...

The same should be done for the second if statement.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

Write a function like this and use if to access indices:

def get(matrix, i, j):
    if 0 <= i < len(matrix):
        if 0 <= j < len(matrix[i]):
            return matrix[i][j]
    return None

UPDATED to handle negative indices. Thanks to BrokenBenchmark

re-za
  • 750
  • 4
  • 10