NumPy: Change marks with masked assignments

Masked assignment changes an array in place where a condition holds. Apply a series of rules to exam marks.

What to build

A program that applies masked assignments to marks and reports the effect.

Requirements

  • Commands: cap V (a[a > V] = V), floor V (a[a < V] = V), add L H K (a[(a >= L) & (a <= H)] += K) and set L H V (a[(a >= L) & (a <= H)] = V). Each command's mask is built from the marks as they are at that moment.
  • After each command print CMD: changed N, where N is how many marks have a new value. At the end print the marks as a Python list.

Input

Line 1: the marks, whole numbers. Line 2: n. Then n commands.

Output

n lines, then the list.

Constraints

1 to 50 marks; 1 ≤ n ≤ 20.

Example

Input:

55 82 47 91 68
2
cap 85
add 45 49 3

Output:

cap 85: changed 1
add 45 49 3: changed 1
[55, 82, 50, 85, 68]

Why it works

A mask is computed once from the current values and then used to change exactly those elements, so a later rule sees the results of earlier ones, and an element whose value did not actually change is not counted.

Examples

Example 1 · Input
55 82 47 91 68
2
cap 85
add 45 49 3
Expected output
cap 85: changed 1
add 45 49 3: changed 1
[55, 82, 50, 85, 68]
Example 2 · Input
10 20 30
2
floor 15
set 15 25 25
Expected output
floor 15: changed 1
set 15 25 25: changed 2
[25, 25, 30]

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

Hints

Hint 1

For each command build the mask from the current marks, then change only those elements.

Hint 2

between L H means L ≤ mark ≤ H, like (a >= L) & (a <= H).

Solution

Show one correct solution (try it yourself first)
a = [int(x) for x in input().split()]
n = int(input())
for _ in range(n):
    line = input()
    parts = line.split()
    cmd, nums = parts[0], [int(x) for x in parts[1:]]
    before = a[:]
    if cmd == "cap":
        a = [nums[0] if v > nums[0] else v for v in a]
    elif cmd == "floor":
        a = [nums[0] if v < nums[0] else v for v in a]
    elif cmd == "add":
        lo, hi, k = nums
        a = [v + k if lo <= v <= hi else v for v in a]
    else:
        lo, hi, value = nums
        a = [value if lo <= v <= hi else v for v in a]
    print(f"{line}: changed {sum(1 for x, y in zip(before, a) if x != y)}")
print(a)

Lesson: Boolean masks and where →