NumPy: Read elements by index

Look up elements of a 2-D array with a[i, j], including negative indices and NumPy's error for an index out of range.

What to build

A program that answers a[i, j] lookups.

Requirements

  • For each query i j, print the element, or NumPy's error for the first axis whose index is out of range: IndexError: index I is out of bounds for axis A with size N.

Input

Line 1: r and c. Then r lines of c whole numbers. Then q, then q queries.

Output

q lines.

Constraints

1 ≤ r, c ≤ 10; 1 ≤ q ≤ 20; |i|, |j| ≤ 50.

Example

Input:

2 3
1 2 3
4 5 6
3
1 2
-1 0
2 0

Output:

6
4
IndexError: index 2 is out of bounds for axis 0 with size 2

Why it works

Negative indices count back from the end, so -1 is the last position; NumPy checks every index against its axis's size before reading.

Examples

Example 1 · Input
2 3
1 2 3
4 5 6
3
1 2
-1 0
2 0
Expected output
6
4
IndexError: index 2 is out of bounds for axis 0 with size 2
Example 2 · Input
1 1
7
2
0 -1
0 1
Expected output
7
IndexError: index 1 is out of bounds for axis 1 with size 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

An index i is valid for an axis of size n when -n ≤ i < n.

Hint 2

Check axis 0 before axis 1, as NumPy does.

Solution

Show one correct solution (try it yourself first)
r, c = map(int, input().split())
a = [input().split() for _ in range(r)]
q = int(input())
for _ in range(q):
    i, j = map(int, input().split())
    if not -r <= i < r:
        print(f"IndexError: index {i} is out of bounds for axis 0 with size {r}")
    elif not -c <= j < c:
        print(f"IndexError: index {j} is out of bounds for axis 1 with size {c}")
    else:
        print(a[i][j])

Lesson: Indexing and slicing →