What is the output of the following code that sums two arrays using a loop and using vectorization?
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) # Using loop result_loop = [] for i in range(len(arr1)): result_loop.append(arr1[i] + arr2[i]) # Using vectorization result_vec = arr1 + arr2 print(result_loop) print(result_vec.tolist())
Think about how element-wise addition works in numpy arrays compared to manual loops.
Both the loop and vectorized code add corresponding elements of the two arrays. The loop creates a list with sums, and vectorization returns a numpy array which is converted to list for printing. Both outputs are the same: [5, 7, 9].
Given two numpy arrays a with shape (3, 1) and b with shape (1, 4), what is the shape of the result after a + b?
import numpy as np a = np.array([[1], [2], [3]]) b = np.array([[10, 20, 30, 40]]) c = a + b print(c.shape)
Remember numpy broadcasting rules for arrays with different shapes.
Array a has shape (3,1) and b has shape (1,4). Broadcasting expands them to (3,4) each before addition, so the result shape is (3,4).
What error does the following code raise?
import numpy as np arr = np.array([1, 2, 3]) result = arr + '4' print(result)
Think about adding numbers and strings in numpy arrays.
You cannot add a numpy array of integers and a string directly. This raises a TypeError about unsupported operand types.
You have two sets of points in 2D space stored as numpy arrays A (shape (m, 2)) and B (shape (n, 2)). Which option correctly computes the matrix of Euclidean distances between each point in A and each point in B using vectorization?
import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8], [9, 10]])
Use broadcasting to subtract each point in B from each point in A, then sum squared differences.
Option B uses broadcasting to create a (m, n, 2) array of differences, squares them, sums over coordinates, and takes square root to get Euclidean distances matrix of shape (m, n).
Which of the following best explains why vectorized operations in numpy are faster than explicit Python loops?
Think about what happens under the hood when numpy runs vectorized code.
Numpy vectorized operations run compiled C code internally, avoiding slow Python loops and function calls, which makes them faster. They do not automatically use multiple cores or GPUs.