Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a memory-mapped array from a file.
NumPy
import numpy as np mmap_array = np.memmap('data.dat', dtype='float32', mode=[1], shape=(1000, 1000))
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w+' mode when the file does not exist causes an error.
Using 'r+' mode without write permission causes an error.
✗ Incorrect
The mode 'r' opens the file for reading only, which is common for memory-mapped arrays when you don't want to modify the data.
2fill in blank
mediumComplete the code to write data to a new memory-mapped file.
NumPy
import numpy as np mmap_array = np.memmap('new_data.dat', dtype='int32', mode=[1], shape=(500, 500)) mmap_array[:] = np.arange(250000).reshape(500, 500) mmap_array.flush()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode which does not allow writing.
Using 'r+' mode without an existing file.
✗ Incorrect
The mode 'w+' creates a new file or overwrites an existing one and allows reading and writing.
3fill in blank
hardFix the error in the code to correctly access the memory-mapped array slice.
NumPy
import numpy as np mmap_array = np.memmap('data.dat', dtype='float64', mode='r', shape=(100, 100)) slice_data = mmap_array[[1]]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using commas inside the brackets which is invalid for slicing.
Adding extra brackets around the slice.
✗ Incorrect
To slice rows 50 to 59, use the slice notation 50:60 without extra brackets or commas.
4fill in blank
hardFill both blanks to create a memory-mapped array and then read a specific element.
NumPy
import numpy as np mmap_array = np.memmap('file.dat', dtype=[1], mode='r', shape=(10, 10)) element = mmap_array[[2]]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a tuple for dtype instead of a string.
Using a single index instead of two for a 2D array.
✗ Incorrect
The dtype should be 'float64' to match the data type, and the element at row 5, column 5 is accessed by mmap_array[5, 5].
5fill in blank
hardFill all three blanks to create a writable memory-mapped array, modify it, and save changes.
NumPy
import numpy as np mmap_array = np.memmap('mod_data.dat', dtype=[1], mode=[2], shape=(20, 20)) mmap_array[10, 10] = [3] mmap_array.flush()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using mode 'r' which does not allow writing.
Assigning a value without matching dtype.
✗ Incorrect
Use dtype 'float32' for the array, mode 'r+' to allow writing, and assign 42.0 to the element at position (10, 10).