Challenge - 5 Problems
Memmap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of np.memmap array modification
What is the output of the following code snippet?
NumPy
import numpy as np filename = 'data.dat' # Create a memmap file with 5 integers arr = np.memmap(filename, dtype='int32', mode='w+', shape=(5,)) arr[:] = np.arange(5) arr.flush() # Reopen in read mode arr2 = np.memmap(filename, dtype='int32', mode='r', shape=(5,)) print(arr2[2])
Attempts:
2 left
💡 Hint
Remember that np.memmap writes data to disk and reopening in read mode reads the saved data.
✗ Incorrect
The memmap file is created and filled with values 0 to 4. Reopening in read mode reads the saved data, so arr2[2] is 2.
❓ data_output
intermediate2:00remaining
Shape of np.memmap array after reshaping
Given this code, what is the shape of the memmap array after reshaping?
NumPy
import numpy as np filename = 'data2.dat' arr = np.memmap(filename, dtype='float64', mode='w+', shape=(12,)) arr[:] = np.arange(12) arr.flush() arr2 = np.memmap(filename, dtype='float64', mode='r+', shape=(3,4)) print(arr2.shape)
Attempts:
2 left
💡 Hint
The shape parameter defines how the data is viewed, not the original file size.
✗ Incorrect
The memmap is reopened with shape (3,4), so arr2.shape is (3,4).
🔧 Debug
advanced2:00remaining
Identify the error in np.memmap usage
What error does this code raise?
NumPy
import numpy as np filename = 'data3.dat' arr = np.memmap(filename, dtype='int16', mode='w+', shape=(10,)) arr[:] = np.arange(10) arr.flush() # Reopen with wrong dtype arr2 = np.memmap(filename, dtype='int32', mode='r', shape=(10,)) print(arr2[0])
Attempts:
2 left
💡 Hint
The file was saved with int16 (2 bytes per element), but reopened as int32 (4 bytes per element).
✗ Incorrect
The memmap file size does not match the expected size for int32 with shape (10,), causing a buffer size mismatch error.
🚀 Application
advanced3:00remaining
Efficiently modifying large data with np.memmap
You have a large binary file with 1 million float64 numbers. You want to add 10 to every element without loading the entire file into memory. Which code snippet correctly does this?
Attempts:
2 left
💡 Hint
Mode 'r+' allows read and write. Vectorized operations may load all data into memory.
✗ Incorrect
Option B modifies elements one by one, avoiding loading entire file into memory. Option B uses vectorized addition which loads all data, Option B is read-only mode, Option B overwrites all data with 10.
🧠 Conceptual
expert2:00remaining
Understanding np.memmap file persistence
Which statement about np.memmap file persistence is TRUE?
Attempts:
2 left
💡 Hint
Think about when data is guaranteed to be written to disk.
✗ Incorrect
flush() forces changes to be written to disk. Without flush(), changes may remain in OS cache and not be saved immediately.