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 STEPmakes a view of the base likea[START:STOP:STEP];copy NAME START STOP STEPmakes a copy of the same elements;set NAME I Vsets element I of NAME (the base is calleda);show NAMEprints 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
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
[10, 99, 30, 40, 50, 60] [20, 40]
1 2 3 4 4 view v 0 4 1 set a 3 -4 set v 0 -1 show v
[-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])