NumPy: Division with inf and nan

NumPy does not stop on division by zero: it gives inf, -inf or nan and warns. Model a / b element by element.

What to build

A program that divides two arrays as NumPy does.

Requirements

  • Print each result of a / b with 2 decimal places, or inf, -inf or nan, separated by spaces.
  • Before the results, print RuntimeWarning: divide by zero encountered in divide if any non-zero value was divided by 0, then RuntimeWarning: invalid value encountered in divide if any 0 was divided by 0.
  • If the arrays have different lengths, print only ValueError: operands could not be broadcast together with shapes (N,) (M,).

Input

Line 1: a's whole numbers. Line 2: b's whole numbers.

Output

The warnings, then the results.

Constraints

1 to 30 numbers per line; |x| ≤ 10^6.

Example

Input:

1 -1 0 6
0 0 0 4

Output:

RuntimeWarning: divide by zero encountered in divide
RuntimeWarning: invalid value encountered in divide
inf -inf nan 1.50

Why it works

Floating-point division has defined answers for zero divisors, so NumPy finishes the whole array and reports problems as warnings rather than stopping at the first one.

Examples

Example 1 · Input
1 -1 0 6
0 0 0 4
Expected output
RuntimeWarning: divide by zero encountered in divide
RuntimeWarning: invalid value encountered in divide
inf -inf nan 1.50
Example 2 · Input
10 20 30
4 5 6
Expected output
2.50 4.00 5.00

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

Hints

Hint 1

For b = 0: a positive a gives inf, a negative a gives -inf, and 0 gives nan.

Hint 2

Remember which warnings happened, and print each kind once.

Solution

Show one correct solution (try it yourself first)
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
if len(a) != len(b):
    print(f"ValueError: operands could not be broadcast together with shapes ({len(a)},) ({len(b)},)")
else:
    out, zero, invalid = [], False, False
    for x, y in zip(a, b):
        if y != 0:
            out.append(f"{x / y:.2f}")
        elif x == 0:
            invalid = True
            out.append("nan")
        else:
            zero = True
            out.append("inf" if x > 0 else "-inf")
    if zero:
        print("RuntimeWarning: divide by zero encountered in divide")
    if invalid:
        print("RuntimeWarning: invalid value encountered in divide")
    print(" ".join(out))

Lesson: Vectorised arithmetic and ufuncs →