QUESTION 28 Predict the output of the following Python program:
Micron technical mcq question, verified with a worked answer. Free to practise - no sign-up.
QUESTION 28
Predict the output of the following Python program:
import numpy as np
x = np.arange(12).reshape((2, 6))
r1 = np.ptp(x, 1)
r2 = np.amax(x, 1) - np.amin(x, 1)
assert np.allclose(r1, r2)
print(r1)
Show answer & explanation
np.arange(12) creates [0, 1, 2, ..., 11], reshaped to a 2×6 matrix: [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]. np.ptp(x, 1) computes the peak-to-peak (max - min) along axis 1 for each row: row 0 has max 5, min 0 → 5; row 1 has max 11, min 6 → 5. The assertion verifies this matches np.amax(x, 1) - np.amin(x, 1), which it does. Output is [5 5].
Step-by-step Derivation:
Step 1: x = np.arange(12).reshape((2, 6))
Result: x = [[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11]]
Step 2: r1 = np.ptp(x, 1) — peak-to-peak along axis 1 (rows)
Row 0: max(0,1,2,3,4,5) - min(0,1,2,3,4,5) = 5 - 0 = 5
Row 1: max(6,7,8,9,10,11) - min(6,7,8,9,10,11) = 11 - 6 = 5
Result: r1 = [5, 5]
Step 3: r2 = np.amax(x, 1) - np.amin(x, 1)
np.amax(x, 1) = [5, 11]
np.amin(x, 1) = [0, 6]
r2 = [5, 11] - [0, 6] = [5, 5]
Step 4: assert np.allclose(r1, r2) passes (both are [5, 5])
Step 5: print(r1) outputs [5 5]