Challenge - 5 Problems
Memory Mastery in NumPy
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of modifying a NumPy view
What is the output of the following code?
import numpy as np arr = np.array([1, 2, 3, 4]) view = arr[1:3] view[0] = 10 print(arr)
NumPy
import numpy as np arr = np.array([1, 2, 3, 4]) view = arr[1:3] view[0] = 10 print(arr)
Attempts:
2 left
💡 Hint
Remember that views share memory with the original array.
✗ Incorrect
The slice creates a view, so changing view[0] changes arr[1]. The original array updates at index 1.
❓ data_output
intermediate1:30remaining
Memory sharing check with np.shares_memory
Given the code below, what does the print statement output?
import numpy as np x = np.arange(5) y = x[2:] print(np.shares_memory(x, y))
NumPy
import numpy as np x = np.arange(5) y = x[2:] print(np.shares_memory(x, y))
Attempts:
2 left
💡 Hint
Slices usually share memory with the original array.
✗ Incorrect
The slice y is a view of x, so they share memory. np.shares_memory returns True.
🔧 Debug
advanced2:00remaining
Why does modifying a copy not affect the original?
Consider this code:
Why does the original array not change?
import numpy as np arr = np.array([5, 6, 7, 8]) copied = arr.copy() copied[0] = 100 print(arr)
Why does the original array not change?
NumPy
import numpy as np arr = np.array([5, 6, 7, 8]) copied = arr.copy() copied[0] = 100 print(arr)
Attempts:
2 left
💡 Hint
Think about what .copy() does to the data.
✗ Incorrect
The .copy() method creates a new array with its own memory, so changes to copied do not affect arr.
🚀 Application
advanced2:30remaining
Detecting if two arrays share memory
You have two arrays:
Which code snippet correctly detects which arrays share memory with base?
import numpy as np base = np.array([1, 2, 3, 4, 5]) arr1 = base[1:4] arr2 = base.copy()[1:4]
Which code snippet correctly detects which arrays share memory with base?
NumPy
import numpy as np base = np.array([1, 2, 3, 4, 5]) arr1 = base[1:4] arr2 = base.copy()[1:4]
Attempts:
2 left
💡 Hint
Remember that slicing creates views but copy() creates independent arrays.
✗ Incorrect
arr1 is a view and shares memory with base, arr2 is a slice of a copy and does not share memory.
🧠 Conceptual
expert3:00remaining
Effect of modifying a view on a reshaped array
Given the code below, what is the output?
import numpy as np original = np.arange(6) reshaped = original.reshape(2, 3) view = reshaped[:, 1] view[0] = 99 print(original)
NumPy
import numpy as np original = np.arange(6) reshaped = original.reshape(2, 3) view = reshaped[:, 1] view[0] = 99 print(original)
Attempts:
2 left
💡 Hint
Think about how reshaping and slicing create views sharing memory.
✗ Incorrect
The view selects the second column of reshaped, which corresponds to original indices 1 and 4. Changing view[0] changes original[1].