NumPy: Choose values with np.where

np.where(condition, x, y) builds a new array element by element. Model it with comparisons and choices.

What to build

A program that evaluates np.where expressions on an array.

Requirements

  • Each query is OP T X Y, meaning np.where(a OP T, X, Y), where OP is one of >, >=, <, <=, ==, !=, and X and Y are each either a (the array's element) or a whole number.
  • Print each result in NumPy's 1-D format (brackets, numbers right-aligned to the widest, single spaces).

Input

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

Output

q lines.

Constraints

1 to 30 numbers; 1 ≤ q ≤ 20; |values| ≤ 10^6.

Example

Input:

4 9 1 7
2
> 5 a 0
<= 4 -1 a

Output:

[0 9 0 7]
[-1  9 -1  7]

Why it works

where is a choice made separately for every element: the condition decides, and the two choices can be the element itself or a fixed value, so the result always has the array's shape.

Examples

Example 1 · Input
4 9 1 7
2
> 5 a 0
<= 4 -1 a
Expected output
[0 9 0 7]
[-1  9 -1  7]
Example 2 · Input
1 2 3
1
== 2 100 0
Expected output
[  0 100   0]

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

Hints

Hint 1

Parse each choice: the word a means the array's own element, anything else is a number.

Hint 2

Build the condition per element, then pick x or y.

Solution

Show one correct solution (try it yourself first)
OPS = {">": lambda v, t: v > t, ">=": lambda v, t: v >= t, "<": lambda v, t: v < t, "<=": lambda v, t: v <= t, "==": lambda v, t: v == t, "!=": lambda v, t: v != t}

a = [int(x) for x in input().split()]
q = int(input())
for _ in range(q):
    op, t, x, y = input().split()
    t = int(t)
    pick = lambda choice, v: v if choice == "a" else int(choice)
    result = [pick(x, v) if OPS[op](v, t) else pick(y, v) for v in a]
    w = max(len(str(v)) for v in result)
    print("[" + " ".join(str(v).rjust(w) for v in result) + "]")

Lesson: Boolean masks and where →