NumPy: Writes through views

Model several views and copies of one array and follow what each write changes.

What to build

A program that applies writes to views and copies of a base array.

Requirements

  • Commands: view NAME START STOP STEP makes a view of the base like a[START:STOP:STEP]; copy NAME START STOP STEP makes a copy of the same elements; set NAME I V sets element I of NAME (the base is called a); show NAME prints NAME's current values as a Python list.
  • A view always shows the base's current values at its positions; a copy keeps its own values.

Input

Line 1: the base's whole numbers. Line 2: n. Then n commands.

Output

One line per show.

Constraints

1 to 30 numbers; 1 ≤ n ≤ 40; indices are valid for their array; steps are not 0.

Example

Input:

10 20 30 40 50 60
5
view b 1 5 2
copy c 1 5 2
set b 0 99
show a
show c

Output:

[10, 99, 30, 40, 50, 60]
[20, 40]

Why it works

A view stores where to look, not what it saw, so any write to the base, directly or through another view, is visible in it; a copy stored the values themselves, so later writes elsewhere never reach it.

Examples

Example 1 · Input
10 20 30 40 50 60
5
view b 1 5 2
copy c 1 5 2
set b 0 99
show a
show c
Expected output
[10, 99, 30, 40, 50, 60]
[20, 40]
Example 2 · Input
1 2 3 4
4
view v 0 4 1
set a 3 -4
set v 0 -1
show v
Expected output
[-1, 2, 3, -4]

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

Hints

Hint 1

Store a view as the list of positions it sees in the base; a copy as its own list.

Hint 2

Writing through a view changes the base, so every other view sees it too.

Solution

Show one correct solution (try it yourself first)
base = [int(x) for x in input().split()]
views = {}
copies = {"a": None}
n = int(input())
for _ in range(n):
    parts = input().split()
    cmd, name = parts[0], parts[1]
    if cmd in ("view", "copy"):
        start, stop, step = map(int, parts[2:])
        positions = list(range(len(base)))[start:stop:step]
        if cmd == "view":
            views[name] = positions
            copies.pop(name, None)
        else:
            copies[name] = [base[p] for p in positions]
            views.pop(name, None)
    elif cmd == "set":
        i, v = int(parts[2]), int(parts[3])
        if name == "a":
            base[i] = v
        elif name in views:
            base[views[name][i]] = v
        else:
            copies[name][i] = v
    else:
        if name == "a":
            print(base)
        elif name in views:
            print([base[p] for p in views[name]])
        else:
            print(copies[name])

Lesson: Views and copies →