Challenge - 5 Problems
Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of slicing specific rows and columns in a NumPy array
What is the output of the following code snippet that slices rows and columns from a NumPy array?
NumPy
import numpy as np arr = np.array([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160]]) result = arr[1:3, 2:4] print(result)
Attempts:
2 left
💡 Hint
Remember that slicing arr[a:b, c:d] selects rows from a to b-1 and columns from c to d-1.
✗ Incorrect
The slice arr[1:3, 2:4] selects rows 1 and 2, and columns 2 and 3. So it picks elements [[70, 80], [110, 120]].
❓ data_output
intermediate1:30remaining
Number of elements after slicing rows and columns
Given the NumPy array below, how many elements are in the sliced array `arr[::2, 1:4:2]`?
NumPy
import numpy as np arr = np.arange(24).reshape(4,6) sliced = arr[::2, 1:4:2] print(sliced)
Attempts:
2 left
💡 Hint
Count how many rows and columns are selected by the slice.
✗ Incorrect
arr[::2, 1:4:2] selects every 2nd row starting at 0 (rows 0 and 2) and columns 1 and 3 (since 1:4:2 means columns 1 and 3). So 2 rows * 2 columns = 4 elements.
🔧 Debug
advanced2:00remaining
Identify the error in slicing a 2D NumPy array
What error will the following code raise when slicing the array?
NumPy
import numpy as np arr = np.array([[1,2,3],[4,5,6],[7,8,9]]) result = arr[1, 2:] print(result[1])
Attempts:
2 left
💡 Hint
Check the shape of the sliced array before accessing index 1.
✗ Incorrect
arr[1, 2:] returns a 1D array [6,] of length 1 (row 1, columns from 2 to end). Accessing result[1] raises IndexError: index 1 is out of bounds for axis 0 with size 1.
❓ visualization
advanced2:30remaining
Visualize the sliced subarray from a heatmap
Given the heatmap of a 5x5 array, which sliced subarray corresponds to `arr[1:4, 0:3]`?
NumPy
import numpy as np import matplotlib.pyplot as plt arr = np.arange(25).reshape(5,5) plt.imshow(arr, cmap='viridis') plt.colorbar() plt.title('Original 5x5 Array Heatmap') plt.show()
Attempts:
2 left
💡 Hint
Remember slicing rows 1 to 3 and columns 0 to 2 means rows 1,2,3 and columns 0,1,2.
✗ Incorrect
arr[1:4, 0:3] selects rows 1,2,3 and columns 0,1,2. The values are [[5,6,7],[10,11,12],[15,16,17]].
🚀 Application
expert3:00remaining
Extract diagonal blocks using slicing in a large NumPy array
You have a 6x6 NumPy array representing a matrix divided into four 3x3 blocks. Which slice extracts the bottom-right 3x3 block?
NumPy
import numpy as np matrix = np.arange(36).reshape(6,6) # Extract bottom-right block here block = matrix[3:6, 3:6] print(block)
Attempts:
2 left
💡 Hint
The bottom-right block is the last 3 rows and last 3 columns.
✗ Incorrect
The 6x6 matrix is split into four 3x3 blocks. The bottom-right block is rows 3 to 5 and columns 3 to 5, so matrix[3:6, 3:6].