0
0
NumPydata~10 mins

Views share memory with originals 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 view of the original NumPy array.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
view_arr = arr[1]
Drag options to blanks, or click blank then click option'
A.reshape(2, 2)
B.copy()
C.flatten()
D.view()
Attempts:
3 left
💡 Hint
Common Mistakes
Using .copy() instead of .view() creates a separate array, not a view.
Using .reshape() changes shape but does not guarantee shared memory.
Using .flatten() returns a copy, not a view.
2fill in blank
medium

Complete the code to modify the view and see the change in the original array.

NumPy
import numpy as np
arr = np.array([10, 20, 30, 40])
view_arr = arr.view()
view_arr[1] = [1]
result = arr[1]
Drag options to blanks, or click blank then click option'
A20
B25
C50
D40
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the same original value does not show the effect of shared memory.
Assigning a value outside the array range causes an error.
3fill in blank
hard

Fix the error in the code to confirm if two arrays share memory.

NumPy
import numpy as np
arr = np.array([5, 6, 7, 8])
view_arr = arr.view()
shares_memory = np.shares_memory(arr, [1])
Drag options to blanks, or click blank then click option'
Aview_arr
Barr.copy()
Carr.flatten()
Darr.reshape(2, 2)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing arr.copy() instead of the view array returns False.
Passing reshaped or flattened arrays may or may not share memory depending on the operation.
4fill in blank
hard

Fill both blanks to create a view and modify it to see the effect on the original array.

NumPy
import numpy as np
arr = np.array([100, 200, 300, 400])
view_arr = arr[1]
view_arr[2] = [2]
Drag options to blanks, or click blank then click option'
A.view()
B.copy()
C350
D250
Attempts:
3 left
💡 Hint
Common Mistakes
Using .copy() creates a separate array, so changes do not affect the original.
Assigning the wrong index or value does not demonstrate shared memory.
5fill in blank
hard

Fill all three blanks to create a view, modify it, and check if the original array changed.

NumPy
import numpy as np
arr = np.array([7, 14, 21, 28])
view_arr = arr[1]
view_arr[0] = [2]
changed = arr[0] == [3]
Drag options to blanks, or click blank then click option'
A.view()
B70
D.copy()
Attempts:
3 left
💡 Hint
Common Mistakes
Using .copy() creates a separate array, so arr[0] does not change.
Assigning a different value than 70 causes the check to fail.