0
0
NumPydata~10 mins

Contiguous memory layout concept in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a contiguous NumPy array from a Python list.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5], [1]='C')
print(arr.flags['C_CONTIGUOUS'])
Drag options to blanks, or click blank then click option'
Aorder
Bcopy
Cdtype
Dshape
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'copy' instead of 'order' will not control memory layout.
Confusing 'dtype' with memory layout parameter.
2fill in blank
medium

Complete the code to check if a NumPy array is stored contiguously in memory.

NumPy
import numpy as np
arr = np.arange(10)
is_contiguous = arr.flags.[1]
print(is_contiguous)
Drag options to blanks, or click blank then click option'
AF_CONTIGUOUS
BWRITEABLE
COWNDATA
DC_CONTIGUOUS
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'F_CONTIGUOUS' checks for Fortran-style layout, not C-style.
Confusing 'OWNDATA' with memory contiguity.
3fill in blank
hard

Fix the error in the code to make the array contiguous after slicing.

NumPy
import numpy as np
arr = np.arange(10)
sliced = arr[::2]
contiguous = sliced.[1]()
print(contiguous.flags['C_CONTIGUOUS'])
Drag options to blanks, or click blank then click option'
Aflatten
Bcopy
Ccontiguous
Dreshape
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'flatten' returns a copy but also changes shape to 1D.
Using 'reshape' without copying may fail if memory is not contiguous.
4fill in blank
hard

Fill both blanks to create a 2D contiguous array and check its memory layout.

NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]], [1]='[2]')
print(arr.flags['C_CONTIGUOUS'])
Drag options to blanks, or click blank then click option'
Aorder
Bcopy
CC
DF
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'F' instead of 'C' creates Fortran-style layout.
Using 'copy' as parameter name is incorrect.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps words to their lengths only if the length is greater than 3.

NumPy
words = ['data', 'science', 'ai', 'ml']
lengths = { [1]: [2] for word in words if [3] }
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
Clen(word) > 3
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word > 3' is invalid because words are strings.
Using 'len(word)' as key instead of value.