Step 1: Understand slicing with step and contiguity
arr = np.arange(10)[::2] creates a non-contiguous view with step 2.
Step 2: Use np.ascontiguousarray to copy contiguous
np.ascontiguousarray(arr) returns a contiguous copy of arr.
Final Answer:
No error, code runs and prints True -> Option D
Quick Check:
ascontiguousarray fixes contiguity = True [OK]
Hint: ascontiguousarray copies to contiguous memory [OK]
Common Mistakes:
Thinking ascontiguousarray does not exist
Assuming original array is contiguous after slicing with step
Expecting cont_arr to be a view, not a copy
5. You have a large 2D numpy array data that is a transpose of a contiguous array. You want to speed up computations that require contiguous memory. What is the best way to get a contiguous array without changing the data values?
hard
A. Use np.ascontiguousarray(data) to get a contiguous array
B. Use data.copy(order='K') to get a contiguous copy
C. Use data.T again to reverse transpose
D. Use data.flatten() to get a 1D contiguous array
Solution
Step 1: Understand transpose effect on contiguity
Transposing an array usually breaks contiguity because rows and columns swap.
Step 2: Choose method to get contiguous array without changing data
np.ascontiguousarray returns a contiguous array copy without changing data values.
Step 3: Evaluate other options
data.copy(order='K') preserves the original layout (F-contiguous), so flags['C_CONTIGUOUS'] remains False; data.T reverses transpose but changes shape; flatten() changes shape to 1D, which may not be desired.
Final Answer:
Use np.ascontiguousarray(data) to get a contiguous array -> Option A