Challenge - 5 Problems
Randomness Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1: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())
Attempts:
2 left
💡 Hint
Remember that
integers(low, high) generates numbers from low (inclusive) to high (exclusive).✗ Incorrect
The
default_rng with seed 42 produces a fixed sequence. The call rng.integers(1, 5, size=4) generates four integers between 1 and 4 inclusive. The exact output list is [4, 1, 1, 4].❓ data_output
intermediate1: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)
Attempts:
2 left
💡 Hint
The
size parameter defines the shape of the output array.✗ Incorrect
The
rng.normal function generates samples from a normal distribution. The size=(3, 2) means the output array has 3 rows and 2 columns, so shape is (3, 2).🔧 Debug
advanced1: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])
Attempts:
2 left
💡 Hint
Check the length of the probability array compared to the choices array.
✗ Incorrect
The
p parameter must have the same length as the array to choose from. Here, the array has length 3 but p has length 2, causing a ValueError.🧠 Conceptual
advanced1:00remaining
Understanding seed behavior in default_rng
Which statement about
np.random.default_rng(seed) is true?Attempts:
2 left
💡 Hint
Think about reproducibility in random number generation.
✗ Incorrect
The seed initializes the random number generator. Using the same seed ensures the same sequence of random numbers, which helps with reproducibility.
🚀 Application
expert2: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')})
Attempts:
2 left
💡 Hint
Pandas
sample expects an int or np.random.RandomState for random_state, but default_rng returns a Generator.✗ Incorrect
Pandas
sample does not accept np.random.Generator directly as random_state. Using rng.permutation to shuffle indices and then reindexing is the correct reproducible approach.