{ }codelper
referencescopying listsP0406

Lists inside lists and shallow copies

Follow a small ledger of named lists.
An item of a list is either an integer or another list.
Putting a list into another list puts that very list in, not a copy.
So if you change that list afterwards, the change shows everywhere that list is contained.
The first line gives the number of commands q, and the next q lines give one command each.
- new x: make a new empty list named x.
- copy x y: make a new list named x holding the items currently in y, in the same order.
An integer item is copied as its value, and a list item is stored as that very list (inner lists are not copied).
After that, adding items to the end of x or y does not show in the other.
- num x v: add the integer v to the end of x.
- put x y: add the list y itself to the end of x.
- show x: print list x on one line.
Write [, then the items joined by commas, then ].
An integer item is written as the number, and a list item is written the same way.
Write no spaces; an empty list is [].
The same list may be in several lists, and may appear several times in one list.
show writes the list in full at every place it appears.
Do not copy inner lists when putting or copying; store something that points at the list (a reference).
Only the output is graded.

Input
1 ≤ q ≤ 2,000.
Names are 1–10 lowercase English letters and digits.
The x of new and copy is a name that has not appeared before; the y of copy and the names in num, put and show were already made by an earlier new or copy.
So each name points at the same list to the end.
v is an integer from 0 to 1,000 (no leading zeros).
In put x y, x and y are different names, and list x is not contained anywhere inside list y at any depth (so no list ever contains itself).
There is at least one show, each show line has at most 2,000 characters, and the whole output, newlines included, has at most 100,000 characters
Output
One line per show, in the order of the commands
Example 1 · stdin
11
new a
num a 1
new b
put a b
num b 2
copy c a
num c 3
num b 4
show a
show c
show b
stdout
[1,[2,4]]
[1,[2,4],3]
[2,4]
Example 2 · stdin
13
new box
new bag
num bag 7
put box bag
put box bag
new e
copy pack box
put pack box
put pack e
num bag 8
show pack
show box
show e
stdout
[[7,8],[7,8],[[7,8],[7,8]],[]]
[[7,8],[7,8]]
[]
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

This problem accepts all 8 languages.
To put 'that very list' into a list, lists must be handled by reference.
Python list, JavaScript/TypeScript arrays, Java ArrayList, C# List<object> and Craykon lists are references, so x.append(y), x.push(y), x.add(y), x.Add(y) and Craykon x.Add(y) are the answer as they are.
C++ std::vector is a value and is copied whole when stored, so store std::shared_ptr<List>; in C store the List * address.
Items that mix numbers and lists are told apart with Python isinstance(t, list), Java instanceof List<?> and C# is List<object> inner, and TypeScript writes them as type Item = number | Item[].
C and C++ use a struct holding a number and a list address.
Craykon cannot ask whether a value is a number or a list, so items are stored as pairs [0, number] and [1, list].
copy is a shallow copy: Python a.copy(), JS/TS [...a], Java new ArrayList<>(a), C# new List<object>(a), C++ std::make_shared<List>(*p) (the inner shared_ptrs are copied and still point at the same lists), C moves the slots one by one, Craykon a.GetRange(0, a.Count).
For the output, JS/TS JSON.stringify(a) gives exactly this format; the other languages write a recursive function.
Trap one: copying when putting (Python x.append(y.copy()), adding Craykon y.GetRange(0, y.Count), storing std::vector by value in C++) hides later changes to y from x.
The first line of example 1 becomes [1,[]] instead of [1,[2,4]].
Trap two: making copy a deep copy (Python copy.deepcopy, JS structuredClone, rebuilding inner lists in C) hides changes made to inner lists after the copy.
The second line of example 1 becomes [1,[2],3].
Trap three: letting copy point at the same list instead of copying (JS lists.set(x, lists.get(y))) makes the 3 added to c show in a too, so the first line of example 1 becomes [1,[2,4],3].
Trap four: the built-in string conversions use other formats.
Java toString() and Python str() put a space after each comma, as in [1, [2, 4]] (in Python .replace(" ", "") removes them).
C# List<object>.ToString() gives System.Collections.Generic.List`1[System.Object], and Craykon Console.WriteLine(list) joins the items with spaces. Trap five: a line may have 2,000 characters, so lists may be nested 1,000 deep. Python's recursion limit is 1,000, so unfolding with a recursive function raises RecursionError. Calling it inside a comprehension also uses two frames per level, so raise the limit with sys.setrecursionlimit(10000).

Pythonmain.py · 31 lines
import sys sys.setrecursionlimit(10000)  # 1000겹까지 들어갈 수 있다. show 한 겹에 프레임이 둘씩 쓰인다  def show(a):    # 항목이 목록이면 그 목록을 같은 꼴로 펼친다(같은 목록이 여러 번 들어 있으면 그때마다)    return "[" + ",".join(show(t) if isinstance(t, list) else str(t) for t in a) + "]"  def main():    lines = sys.stdin.read().split("\n")    q = int(lines[0])    lists = {}  # 이름 → 목록. 목록은 참조라서 담아도, 다른 목록에 넣어도 복사되지 않는다    out = []    for line in lines[1 : q + 1]:        p = line.split()        if p[0] == "new":            lists[p[1]] = []        elif p[0] == "copy":            lists[p[1]] = lists[p[2]].copy()  # 얕은 복사: 겉 목록만 새로, 안의 목록은 같은 것        elif p[0] == "num":            lists[p[1]].append(int(p[2]))        elif p[0] == "put":            lists[p[1]].append(lists[p[2]])  # 목록 그 자체를 넣는다        else:            out.append(show(lists[p[1]]))    sys.stdout.write("\n".join(out) + "\n")  main()
JavaScriptmain.js · 13 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);const lists = new Map(); // 이름 → 배열. 배열은 참조라서 다른 배열에 넣어도 복사되지 않는다const out = [];for (let i = 1; i <= q; i++) {  const [cmd, x, y] = lines[i].trim().split(" ");  if (cmd === "new") lists.set(x, []);  else if (cmd === "copy") lists.set(x, [...lists.get(y)]); // 얕은 복사: 안의 배열은 같은 것  else if (cmd === "num") lists.get(x).push(Number(y));  else if (cmd === "put") lists.get(x).push(lists.get(y)); // 배열 그 자체를 넣는다  else out.push(JSON.stringify(lists.get(x))); // [1,[2,4]]처럼 빈칸 없이 펼쳐 준다}console.log(out.join("\n"));
TypeScriptmain.ts · 18 lines
import { readFileSync } from "node:fs"; type Item = number | Item[]; // 수이거나, 같은 꼴의 항목을 담은 배열 const lines: string[] = readFileSync(0, "utf8").split("\n");const q: number = Number(lines[0]);const lists = new Map<string, Item[]>(); // 이름 → 배열. 배열은 참조라서 다른 배열에 넣어도 복사되지 않는다const get = (name: string): Item[] => lists.get(name)!;const out: string[] = [];for (let i = 1; i <= q; i++) {  const [cmd, x, y] = lines[i].trim().split(" ");  if (cmd === "new") lists.set(x, []);  else if (cmd === "copy") lists.set(x, [...get(y)]); // 얕은 복사: 안의 배열은 같은 것  else if (cmd === "num") get(x).push(Number(y));  else if (cmd === "put") get(x).push(get(y)); // 배열 그 자체를 넣는다  else out.push(JSON.stringify(get(x))); // [1,[2,4]]처럼 빈칸 없이 펼쳐 준다}console.log(out.join("\n"));
JavaMain.java · 46 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; public class Main {    // 항목은 Integer이거나 List<Object>다. 펼쳐서 빈칸 없이 쓴다    static void show(List<Object> a, StringBuilder sb) {        sb.append('[');        for (int k = 0; k < a.size(); k++) {            if (k > 0) sb.append(',');            Object t = a.get(k);            if (t instanceof List<?>) {                @SuppressWarnings("unchecked")                List<Object> inner = (List<Object>) t;                show(inner, sb);            } else {                sb.append(t);            }        }        sb.append(']');    }     public static void main(String[] args) throws Exception {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int q = Integer.parseInt(in.readLine().trim());        Map<String, List<Object>> lists = new HashMap<>(); // 이름 → 목록(참조)        StringBuilder out = new StringBuilder();        for (int i = 0; i < q; i++) {            String[] p = in.readLine().trim().split(" ");            switch (p[0]) {                case "new" -> lists.put(p[1], new ArrayList<>());                case "copy" -> lists.put(p[1], new ArrayList<>(lists.get(p[2]))); // 얕은 복사: 안의 목록은 같은 것                case "num" -> lists.get(p[1]).add(Integer.parseInt(p[2]));                case "put" -> lists.get(p[1]).add(lists.get(p[2])); // 목록 그 자체를 넣는다                default -> {                    show(lists.get(p[1]), out);                    out.append('\n');                }            }        }        System.out.print(out);    }}
C#Main.cs · 39 lines
using System;using System.Collections.Generic;using System.Text; class Program{    // 항목은 int이거나 List<object>다. 펼쳐서 빈칸 없이 쓴다    static void Show(List<object> a, StringBuilder sb)    {        sb.Append('[');        for (int k = 0; k < a.Count; k++)        {            if (k > 0) sb.Append(',');            if (a[k] is List<object> inner) Show(inner, sb);            else sb.Append((int)a[k]);        }        sb.Append(']');    }     static void Main()    {        int q = int.Parse(Console.ReadLine()!.Trim());        var lists = new Dictionary<string, List<object>>(); // 이름 → 목록(참조)        var sb = new StringBuilder();        for (int i = 0; i < q; i++)        {            string[] p = Console.ReadLine()!.Trim().Split(' ');            switch (p[0])            {                case "new": lists[p[1]] = new List<object>(); break;                case "copy": lists[p[1]] = new List<object>(lists[p[2]]); break; // 얕은 복사: 안의 목록은 같은 것                case "num": lists[p[1]].Add(int.Parse(p[2])); break;                case "put": lists[p[1]].Add(lists[p[2]]); break;                 // 목록 그 자체를 넣는다                default: Show(lists[p[1]], sb); sb.Append('\n'); break;            }        }        Console.Write(sb);    }}
C++main.cpp · 59 lines
#include <iostream>#include <map>#include <memory>#include <string>#include <vector> struct List;using ListPtr = std::shared_ptr<List>; // 항목: 수이거나, 다른 목록을 가리키는 shared_ptr. vector<Item>을 복사해도 안의 목록은 같은 것이다struct Item {    int num;    ListPtr list; // 수이면 비어 있다}; struct List {    std::vector<Item> items;}; void show(const List &l, std::string &out) {    out += '[';    for (size_t k = 0; k < l.items.size(); k++) {        if (k > 0) out += ',';        if (l.items[k].list) show(*l.items[k].list, out);        else out += std::to_string(l.items[k].num);    }    out += ']';} int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    int q;    std::cin >> q;    std::map<std::string, ListPtr> lists; // 이름 → 목록을 가리키는 것    std::string out;    for (int i = 0; i < q; i++) {        std::string cmd, x, y;        std::cin >> cmd >> x;        if (cmd == "new") {            lists[x] = std::make_shared<List>();        } else if (cmd == "copy") {            std::cin >> y;            lists[x] = std::make_shared<List>(*lists[y]); // 얕은 복사: 새 겉 목록, 안의 shared_ptr은 그대로        } else if (cmd == "num") {            int v;            std::cin >> v;            lists[x]->items.push_back({v, nullptr});        } else if (cmd == "put") {            std::cin >> y;            lists[x]->items.push_back({0, lists[y]}); // 목록 그 자체를 넣는다        } else {            show(*lists[x], out);            out += '\n';        }    }    std::cout << out;    return 0;}
Cmain.c · 92 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> struct List; /* 항목: 수이거나, 다른 목록의 주소. 주소만 담으니 목록이 복사되지 않는다 */typedef struct {    int is_list;    int num;    struct List *list;} Item; typedef struct List {    Item *items;    int len, cap;} List; static List *new_list(void) {    List *l = malloc(sizeof *l);    l->len = 0;    l->cap = 4;    l->items = malloc(sizeof(Item) * l->cap);    return l;} static void add(List *l, Item it) {    if (l->len == l->cap) {        l->cap *= 2;        l->items = realloc(l->items, sizeof(Item) * l->cap);    }    l->items[l->len++] = it;} /* 얕은 복사: 칸을 그대로 옮기니 안의 목록은 같은 주소를 가리킨다 */static List *copy_list(const List *src) {    List *l = new_list();    for (int k = 0; k < src->len; k++) add(l, src->items[k]);    return l;} static void show(const List *l) {    putchar('[');    for (int k = 0; k < l->len; k++) {        if (k > 0) putchar(',');        if (l->items[k].is_list) show(l->items[k].list);        else printf("%d", l->items[k].num);    }    putchar(']');} static char names[2000][11];static List *refs[2000];static int count = 0; static List *find(const char *name) {    for (int i = 0; i < count; i++)        if (strcmp(names[i], name) == 0) return refs[i];    return NULL;} static void keep(const char *name, List *l) {    strcpy(names[count], name);    refs[count++] = l;} int main(void) {    int q;    scanf("%d", &q);    for (int i = 0; i < q; i++) {        char cmd[8], x[11], y[11];        scanf("%7s %10s", cmd, x);        if (strcmp(cmd, "new") == 0) {            keep(x, new_list());        } else if (strcmp(cmd, "copy") == 0) {            scanf("%10s", y);            keep(x, copy_list(find(y)));        } else if (strcmp(cmd, "num") == 0) {            Item it = {0, 0, NULL};            scanf("%d", &it.num);            add(find(x), it);        } else if (strcmp(cmd, "put") == 0) {            scanf("%10s", y);            Item it = {1, 0, find(y)}; /* 목록 그 자체(주소)를 넣는다 */            add(find(x), it);        } else {            show(find(x));            putchar('\n');        }    }    return 0;}
Craykonmain.cray · 45 lines
// 크레이콘은 값이 수인지 목록인지 물을 수 없어서, 항목을 [종류, 값] 짝으로 담는다// 종류 0은 수, 1은 목록이다. 목록은 참조라서 짝에 담아도 복사되지 않는다보이기(목록){    조각 = [];    foreach (짝 in 목록)    {        if (짝[0] == 1)        {            조각.Add(보이기(짝[1]));        }        else        {            조각.Add("" + 짝[1]);        }    }    return "[" + 조각.Join(",") + "]";} q = Console.ReadLine().ToNumber();이름표 = Dict(); // 이름 → 목록for (i = 0; i < q; i++){    p = Console.ReadLine().Trim().Split();    x = p[1];    switch (p[0])    {        case "new":            이름표[x] = [];            break;        case "copy":            원본 = 이름표[p[2]];            이름표[x] = 원본.GetRange(0, 원본.Count); // 얕은 복사: 짝은 같은 것, 안의 목록도 같은 것            break;        case "num":            이름표[x].Add([0, p[2].ToNumber()]);            break;        case "put":            이름표[x].Add([1, 이름표[p[2]]]); // 목록 그 자체를 넣는다            break;        default:            Console.WriteLine(보이기(이름표[x]));            break;    }}