Bird
0
0

What is the best way to get a contiguous array without changing the data values?

hard📝 Application Q15 of 15
NumPy - Fundamentals
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?
AUse <code>np.ascontiguousarray(data)</code> to get a contiguous array
BUse <code>data.copy(order='K')</code> to get a contiguous copy
CUse <code>data.T</code> again to reverse transpose
DUse <code>data.flatten()</code> to get a 1D contiguous array
Step-by-Step Solution
Solution:
  1. Step 1: Understand transpose effect on contiguity

    Transposing an array usually breaks contiguity because rows and columns swap.
  2. Step 2: Choose method to get contiguous array without changing data

    np.ascontiguousarray returns a contiguous array copy without changing data values.
  3. 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.
  4. Final Answer:

    Use np.ascontiguousarray(data) to get a contiguous array -> Option A
  5. Quick Check:

    ascontiguousarray fixes contiguity efficiently [OK]
Quick Trick: Use np.ascontiguousarray to ensure contiguous copy [OK]
Common Mistakes:
  • Using data.copy(order='K') which preserves F-contiguity
  • Thinking transpose reverses contiguity
  • Using flatten() changes array shape unexpectedly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes