In NumPy, a[i, j] mixes integers and slices freely, and the mix decides the result's shape. Model it.
What to build
A program that evaluates a[R, C] for a 2-D array.
Requirements
- Each query is
R, C, where each part is a whole number (an index) or a slicestart:stoporstart:stop:stepwith optional parts. - Two integers: print the number. One integer: print the 1-D result in NumPy's 1-D format. Two slices: print the 2-D result in NumPy's 2-D format (one width for the whole result). An empty result prints
[]. - Assume every integer index is in range.
Input
Line 1: r and c. Then r lines of c whole numbers. Then q, then q queries.
Output
The result of each query.
Constraints
1 ≤ r, c ≤ 8; 1 ≤ q ≤ 10; steps are never 0.
Example
Input:
3 4
1 2 3 4
5 6 7 8
9 10 11 12
3
1, 2
:, 1
0:2, 1:3
Output:
7
[ 2 6 10]
[[2 3]
[6 7]]
Why it works
An integer picks one position and drops its axis, while a slice keeps its axis even for one position, so the kinds of the two parts decide whether the result is a number, a row or a block.
Examples
3 4 1 2 3 4 5 6 7 8 9 10 11 12 3 1, 2 :, 1 0:2, 1:3
7 [ 2 6 10] [[2 3] [6 7]]
2 3 1 2 3 4 5 6 2 -1, ::-1 0:1, :
[6 5 4] [[1 2 3]]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Parse each half of the query separately: an integer, or a slice with optional parts.
Hint 2
An integer index removes its axis: two integers give a number, one gives a 1-D array, none gives a 2-D array.
Solution
Show one correct solution (try it yourself first)
def part(text):
text = text.strip()
if ":" not in text:
return int(text)
bits = [int(b) if b.strip() else None for b in text.split(":")]
return slice(*bits)
def fmt1(values):
if not values:
return "[]"
w = max(len(str(v)) for v in values)
return "[" + " ".join(str(v).rjust(w) for v in values) + "]"
def fmt2(rows):
if not rows or not rows[0]:
return "[]"
w = max(len(str(v)) for row in rows for v in row)
lines = ["[" + " ".join(str(v).rjust(w) for v in row) + "]" for row in rows]
return "[" + "\n ".join(lines) + "]"
r, c = map(int, input().split())
a = [[int(x) for x in input().split()] for _ in range(r)]
q = int(input())
for _ in range(q):
left, right = input().split(",")
ri, ci = part(left), part(right)
if isinstance(ri, int) and isinstance(ci, int):
print(a[ri][ci])
elif isinstance(ri, int):
print(fmt1(a[ri][ci]))
elif isinstance(ci, int):
print(fmt1([row[ci] for row in a[ri]]))
else:
print(fmt2([row[ci] for row in a[ri]]))