1

I am writing a function with the parameters d and e. d represents a matrix that the user inputs, and e represents the starting position in the matrix. I was able to define e as the position of the matrix d:

mainIndex = e[0]
secondIndex = e[1]
position = d[row][column]

I have a challenge whereby if the user inputs the position outside of the matrix the user inputted, it returns False; for instance, if the matrix d = [[3,2,1],[6,5,4],[9,8,7]] and e = [3,0], it should return False rather than raising an index out of range error. How do I achieve that?

jpp
  • 159,742
  • 34
  • 281
  • 339
John.Doe
  • 29
  • 4

2 Answers2

1

you should be able to catch the error as follows:

mainIndex = e[0]
secondIndex = e[1]
try:
    position = d[row][column]
except IndexError:
    return False

Source: I want to exception handle 'list index out of range.'

forgetso
  • 2,194
  • 14
  • 33
  • Is there a way of doing it without try and except feature? I'm taking an online introduction to programming course and we were supposed to complete that question with things we have learned (if-statements, loops, basic list methods and simple methods/helper functions) – John.Doe Nov 14 '18 at 16:51
  • You could always check if the requested index is greater than the length of the list. For example: `index=4 if index > len(a): print('This index is out of range')`. It is usually accepted in python to [try first and ask for acceptance later](https://stackoverflow.com/questions/7604636/better-to-try-something-and-catch-the-exception-or-test-if-its-possible-first). – forgetso Nov 14 '18 at 17:00
1

try / except

You can write a function and catch IndexError. I would also advise you don't chain indexers but use arr[row, column] syntax. For example:

d = np.array([[3,2,1],[6,5,4],[9,8,7]])

def get_val(A, idx):
    try:
        return A[tuple(idx)]
    except IndexError:
        return False

e = [3, 0]
f = [0, 2]

get_val(d, e)  # False
get_val(d, f)  # 1

if / else

An alternative, more explicit solution, is possible via an if / else construct:

def get_val(A, idx):
    if all(i < j for i, j in zip(idx, A.shape)):
        return A[tuple(idx)]
    return False

Since we use tuple(idx), both solutions work for arbitrary dimensions.

jpp
  • 159,742
  • 34
  • 281
  • 339