NumPy: Universal functions on the edges

NumPy's ufuncs never stop on bad input: they give nan or inf. Model sqrt, log, exp, abs, floor and ceil, including their edge cases.

What to build

A program that applies ufuncs to an array of numbers.

Requirements

  • For each ufunc name, print NAME: v1 v2 ... with each value to 4 decimal places (Python prints nan, inf and -inf as words).
  • Rules: sqrt of a negative is nan; log of 0 is -inf and of a negative nan; exp above 709.78 is inf; abs, floor and ceil as usual (floor and ceil give whole numbers, printed with 4 decimals).
  • After all ufuncs, print nan or inf results: K, the total count over all lines.

Input

Line 1: numbers. Line 2: n. Then n ufunc names.

Output

n lines, then the count.

Constraints

1 to 20 numbers; |x| ≤ 10^4; 1 ≤ n ≤ 6.

Example

Input:

4 -1 0
2
sqrt
log

Output:

sqrt: 2.0000 nan 0.0000
log: 1.3863 nan -inf
nan or inf results: 3

Why it works

A ufunc must return a value for every element so that the whole array can be processed at once, so out-of-domain inputs become nan and too-large results become inf instead of errors.

Examples

Example 1 · Input
4 -1 0
2
sqrt
log
Expected output
sqrt: 2.0000 nan 0.0000
log: 1.3863 nan -inf
nan or inf results: 3
Example 2 · Input
1 800
1
exp
Expected output
exp: 2.7183 inf
nan or inf results: 1

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

Hints

Hint 1

Return float("nan") or float("inf") yourself where the math module would raise an error.

Hint 2

f"{x:.4f}" prints nan, inf and -inf as those words.

Solution

Show one correct solution (try it yourself first)
import math

def apply(name, x):
    if name == "sqrt":
        return math.sqrt(x) if x >= 0 else float("nan")
    if name == "log":
        if x > 0:
            return math.log(x)
        return float("-inf") if x == 0 else float("nan")
    if name == "exp":
        return math.exp(x) if x <= 709.78 else float("inf")
    if name == "abs":
        return abs(x)
    if name == "floor":
        return float(math.floor(x))
    return float(math.ceil(x))

values = [float(x) for x in input().split()]
n = int(input())
bad = 0
for _ in range(n):
    name = input()
    results = [apply(name, v) for v in values]
    bad += sum(1 for r in results if math.isnan(r) or math.isinf(r))
    print(name + ": " + " ".join(f"{r:.4f}" for r in results))
print("nan or inf results:", bad)

Lesson: Vectorised arithmetic and ufuncs →