0
0
NumPydata~20 mins

np.random.default_rng() modern approach in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Randomness Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Output of random integers with default_rng
What is the output of this code snippet using np.random.default_rng()?
NumPy
import numpy as np
rng = np.random.default_rng(42)
result = rng.integers(1, 5, size=4)
print(result.tolist())
A[1, 3, 2, 2]
B[3, 1, 2, 4]
C[4, 1, 1, 4]
D[2, 4, 3, 1]
Attempts:
2 left
💡 Hint
Remember that integers(low, high) generates numbers from low (inclusive) to high (exclusive).
data_output
intermediate
1:00remaining
Shape of array from random normal distribution
What is the shape of the array produced by this code?
NumPy
import numpy as np
rng = np.random.default_rng()
arr = rng.normal(loc=0, scale=1, size=(3, 2))
print(arr.shape)
A(3, 2)
B(2, 3)
C(6,)
D(3,)
Attempts:
2 left
💡 Hint
The size parameter defines the shape of the output array.
🔧 Debug
advanced
1:30remaining
Identify the error in random choice usage
What error does this code raise?
NumPy
import numpy as np
rng = np.random.default_rng()
result = rng.choice([10, 20, 30], size=3, replace=False, p=[0.2, 0.5])
AValueError: probabilities do not sum to 1
BTypeError: choice() got an unexpected keyword argument 'p'
CNo error, runs successfully
DValueError: probabilities must be same length as array
Attempts:
2 left
💡 Hint
Check the length of the probability array compared to the choices array.
🧠 Conceptual
advanced
1:00remaining
Understanding seed behavior in default_rng
Which statement about np.random.default_rng(seed) is true?
AUsing the same seed always produces the same random sequence.
BThe seed must be a float between 0 and 1.
Cdefault_rng() ignores the seed parameter completely.
DThe seed controls the shape of the output array.
Attempts:
2 left
💡 Hint
Think about reproducibility in random number generation.
🚀 Application
expert
2:00remaining
Generate reproducible shuffled DataFrame rows
You have a pandas DataFrame df. Which code snippet correctly shuffles its rows reproducibly using np.random.default_rng()?
NumPy
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': range(5), 'B': list('abcde')})
A
rng = np.random.default_rng(42)
shuffled_df = df.sample(frac=1, random_state=rng.bit_generator)
B
rng = np.random.default_rng(42)
shuffled_df = df.iloc[rng.permutation(len(df))].reset_index(drop=True)
C
rng = np.random.default_rng(42)
shuffled_df = df.sample(frac=1, random_state=42)
D
rng = np.random.default_rng(42)
shuffled_df = df.sample(frac=1, random_state=rng)
Attempts:
2 left
💡 Hint
Pandas sample expects an int or np.random.RandomState for random_state, but default_rng returns a Generator.