0
0
NumPydata~20 mins

Shuffling arrays in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Shuffle Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this numpy shuffle code?

Consider the following code that shuffles a numpy array. What will be the output?

NumPy
import numpy as np
np.random.seed(0)
arr = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr)
print(arr.tolist())
A[2, 5, 1, 4, 3]
B[4, 1, 3, 5, 2]
C[5, 4, 1, 3, 2]
D[3, 5, 2, 4, 1]
Attempts:
2 left
💡 Hint

Remember that np.random.shuffle shuffles the array in place and the seed fixes the random order.

data_output
intermediate
1:30remaining
How many elements remain in the array after shuffling?

Given this code, how many elements does the array arr have after shuffling?

NumPy
import numpy as np
arr = np.arange(10)
np.random.shuffle(arr)
print(len(arr))
A0
B9
C10
D1
Attempts:
2 left
💡 Hint

Shuffling changes order but not size.

🔧 Debug
advanced
2:00remaining
What error does this code raise?

What error will this code raise when trying to shuffle a tuple?

NumPy
import numpy as np
t = (1, 2, 3, 4)
np.random.shuffle(t)
ATypeError: 'tuple' object does not support item assignment
BValueError: cannot shuffle immutable sequence
CAttributeError: 'tuple' has no attribute 'shuffle'
DNo error, it shuffles the tuple
Attempts:
2 left
💡 Hint

Think about whether tuples can be changed in place.

🚀 Application
advanced
2:30remaining
Which code correctly shuffles rows of a 2D numpy array?

You have a 2D numpy array representing data rows. Which code correctly shuffles the rows but keeps columns intact?

NumPy
import numpy as np
np.random.seed(1)
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
Anp.random.shuffle(arr)
Barr = np.random.shuffle(arr.T)
Cnp.random.permutation(arr)
Darr = np.random.shuffle(arr)
Attempts:
2 left
💡 Hint

Remember np.random.shuffle shuffles in place and returns None.

🧠 Conceptual
expert
3:00remaining
Why does np.random.shuffle behave differently on multi-dimensional arrays compared to np.random.permutation?

Choose the best explanation for the difference in behavior between np.random.shuffle and np.random.permutation when applied to multi-dimensional numpy arrays.

A<code>np.random.shuffle</code> only works on 1D arrays, while <code>np.random.permutation</code> works on any dimension.
B<code>np.random.shuffle</code> shuffles all axes randomly, while <code>np.random.permutation</code> only shuffles the first axis.
C<code>np.random.shuffle</code> returns a new shuffled array, while <code>np.random.permutation</code> shuffles in place.
D<code>np.random.shuffle</code> shuffles only the first axis in place, while <code>np.random.permutation</code> returns a new shuffled copy of the entire array.
Attempts:
2 left
💡 Hint

Think about in-place vs returning new arrays and which axis is shuffled.