NumPy: Slice a 1-D array

Slices take start:stop:step, where any part may be left out. Apply them to an array and print the results the way NumPy does.

What to build

A program that prints a[start:stop:step] for several slices.

Requirements

  • Each query is a slice written as start:stop or start:stop:step, where each part may be empty. Print the selected values in NumPy's 1-D print format (brackets, numbers right-aligned to the widest, single spaces), or [] when nothing is selected.
  • A step of 0 prints ValueError: slice step cannot be zero.

Input

Line 1: the array's whole numbers. Line 2: q. Then q slices.

Output

q lines.

Constraints

1 to 50 numbers; 1 ≤ q ≤ 20; slice parts are whole numbers with |x| ≤ 100.

Example

Input:

1 2 3 4 5 6 7 8
3
2:5
::3
::-2

Output:

[3 4 5]
[1 4 7]
[8 6 4 2]

Why it works

A slice never fails at the edges: starts and stops beyond the array are clipped to it, and a step pointing away from the stop simply selects nothing.

Examples

Example 1 · Input
1 2 3 4 5 6 7 8
3
2:5
::3
::-2
Expected output
[3 4 5]
[1 4 7]
[8 6 4 2]
Example 2 · Input
10 20 30
2
5:9
1:2:0
Expected output
[]
ValueError: slice step cannot be zero

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

Hints

Hint 1

Turn each part into an int, or None when it is empty, and use Python's slice().

Hint 2

Print with NumPy's format: brackets, one width for all numbers.

Solution

Show one correct solution (try it yourself first)
a = [int(x) for x in input().split()]
q = int(input())
for _ in range(q):
    parts = [int(p) if p else None for p in input().split(":")]
    while len(parts) < 3:
        parts.append(None)
    if parts[2] == 0:
        print("ValueError: slice step cannot be zero")
        continue
    picked = a[slice(*parts)]
    if not picked:
        print("[]")
    else:
        width = max(len(str(v)) for v in picked)
        print("[" + " ".join(str(v).rjust(width) for v in picked) + "]")

Lesson: Indexing and slicing →