Loading

Quipoin Menu

Learn • Practice • Grow

python-for-ai / NumPy Arrays
interview

Q1. Scenario: You have a list of 10 million numbers and need to compute their mean. Using pure Python loops is slow. How does NumPy array handle this efficiently?
NumPy arrays store data in contiguous memory and use vectorized operations in C, avoiding Python loops. Example: import numpy as np; arr = np.array(data); mean = arr.mean(). This is much faster (10-100x) because the loop runs in compiled C. NumPy also uses less memory.

Q2. Scenario: Create a 3x3 matrix of zeros, then set the diagonal to 1. Then convert it to a 1D array. Write the code.
import numpy as np; matrix = np.zeros((3,3)); np.fill_diagonal(matrix, 1) or matrix[[0,1,2],[0,1,2]] = 1; flat = matrix.flatten(). Output: [1,0,0,0,1,0,0,0,1]. Identity matrix. Flatten for vector input to neural networks.

Q3. Scenario: You have two numpy arrays a = [1,2,3] and b = [4,5,6]. Compute element-wise product, dot product, and outer product.
elementwise = a * b -> [4,10,18]; dot = np.dot(a,b)=1*4+2*5+3*6=32; outer = np.outer(a,b) -> 3x3 matrix: [[4,5,6],[8,10,12],[12,15,18]]. These operations are fundamental for linear algebra in ML.

Q4. Scenario: Generate 50 random numbers from a standard normal distribution (mean=0, std=1) using NumPy. Then compute the actual mean and standard deviation of the generated array.
arr = np.random.randn(50); mean = arr.mean(); std = arr.std(). Approx mean ~0, std~1. np.random.randn for normal, np.random.rand for uniform. Essential for initializing neural network weights.

Q5. Scenario: You have an array of shape (4,5). Reshape it to (2,10) and also to (20,1). Check the total number of elements.
arr = np.arange(20).reshape(4,5); arr2 = arr.reshape(2,10); arr3 = arr.reshape(20,1); size = arr.size (20). Reshape does not copy data if possible. -1 can be used: arr.reshape(2,-1) automatically computes second dimension. Important for feeding data to models.