NumPy: View or copy?

Sort NumPy expressions into those that return views and those that return copies.

What to build

A program that classifies indexing expressions.

Requirements

  • An expression is a copy when it contains .copy(), .flatten() or .astype(, or when its square brackets hold a list (a[[) or a comparison (<, >, == or != inside the brackets). Otherwise (slices, .T, .reshape(, .ravel()) it is a view.
  • Print EXPRESSION: view or EXPRESSION: copy.

Input

Line 1: n. Then n expressions.

Output

n lines.

Constraints

1 ≤ n ≤ 30.

Example

Input:

4
a[1:3]
a[[0, 2]]
a[a > 5]
a.T

Output:

a[1:3]: view
a[[0, 2]]: copy
a[a > 5]: copy
a.T: view

Why it works

A result that is the same data read with a new start and step can share memory, so NumPy returns a view; one that gathers arbitrary elements or converts them needs new memory, so it is a copy.

Examples

Example 1 · Input
4
a[1:3]
a[[0, 2]]
a[a > 5]
a.T
Expected output
a[1:3]: view
a[[0, 2]]: copy
a[a > 5]: copy
a.T: view
Example 2 · Input
3
a.reshape(2, 3)
a.flatten()
a.ravel()
Expected output
a.reshape(2, 3): view
a.flatten(): copy
a.ravel(): view

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

Hints

Hint 1

Check the copying operations first: copy(), flatten(), astype(, a list inside the brackets, or a comparison inside the brackets.

Hint 2

Everything else in this exercise, slices, .T, reshape and ravel, is a view.

Solution

Show one correct solution (try it yourself first)
def kind(e):
    if ".copy()" in e or ".flatten()" in e or ".astype(" in e or "[[" in e:
        return "copy"
    inside = e[e.find("[") + 1 : e.rfind("]")] if "[" in e else ""
    if any(op in inside for op in ("<", ">", "==", "!=")):
        return "copy"
    return "view"

n = int(input())
for _ in range(n):
    e = input()
    print(f"{e}: {kind(e)}")

Lesson: Views and copies →