NumPy: The strides of a 2-D view

A view is described by an offset and strides into its base's memory. Work them out for 2-D slices.

What to build

A program that describes the view a[R, C] of a C-ordered 2-D array.

Requirements

  • Input: r, c and the itemsize in bytes, then queries R, C where both parts are slices with optional parts.
  • For each query print shape: (h, w), strides: (s0, s1) in bytes, offset: B in bytes from the start of the base, and elements: ..., the flat positions in the base of the view's elements in row order, separated by spaces (or none when the view is empty). Print a blank line between queries.

Input

Line 1: r c itemsize. Line 2: q. Then q queries.

Output

Four lines per query.

Constraints

1 ≤ r, c ≤ 10; itemsize is 1, 2, 4 or 8; steps are not 0.

Example

Input:

3 4 8
2
:, :
::2, 1:3

Output:

shape: (3, 4)
strides: (32, 8)
offset: 0
elements: 0 1 2 3 4 5 6 7 8 9 10 11

shape: (2, 2)
strides: (64, 8)
offset: 8
elements: 1 2 9 10

Why it works

In C order a row is c elements long, so moving down one row skips c × itemsize bytes; a slice only changes where the view starts and how far it steps on each axis, which is why NumPy can make it without copying anything.

Examples

Example 1 · Input
3 4 8
2
:, :
::2, 1:3
Expected output
shape: (3, 4)
strides: (32, 8)
offset: 0
elements: 0 1 2 3 4 5 6 7 8 9 10 11

shape: (2, 2)
strides: (64, 8)
offset: 8
elements: 1 2 9 10
Example 2 · Input
2 3 4
1
:, ::-1
Expected output
shape: (2, 3)
strides: (12, -4)
offset: 8
elements: 2 1 0 5 4 3

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

Hints

Hint 1

A C-ordered (r, c) array with itemsize s has strides (c × s, s); a slice with step k multiplies that axis's stride by k.

Hint 2

slice.indices(n) turns any slice into an exact start, stop and step for an axis of length n.

Solution

Show one correct solution (try it yourself first)
def parse(text):
    bits = [int(b) if b.strip() else None for b in text.strip().split(":")]
    while len(bits) < 3:
        bits.append(None)
    return slice(*bits)

r, c, size = map(int, input().split())
q = int(input())
blocks = []
for _ in range(q):
    left, right = input().split(",")
    rs, re_, rk = parse(left).indices(r)
    cs, ce, ck = parse(right).indices(c)
    rows = list(range(rs, re_, rk))
    cols = list(range(cs, ce, ck))
    elements = [i * c + j for i in rows for j in cols]
    lines = [
        f"shape: ({len(rows)}, {len(cols)})",
        f"strides: ({c * size * rk}, {size * ck})",
        f"offset: {(rs * c + cs) * size}",
        "elements: " + (" ".join(map(str, elements)) if elements else "none"),
    ]
    blocks.append("\n".join(lines))
print("\n\n".join(blocks))

Lesson: Views and copies →