0
0
NumPydata~20 mins

Generating random samples in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Random Sampling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of numpy random choice with replace=False
What is the output of this code snippet?
import numpy as np
np.random.seed(0)
sample = np.random.choice([10, 20, 30, 40, 50], size=3, replace=False)
print(sample)
NumPy
import numpy as np
np.random.seed(0)
sample = np.random.choice([10, 20, 30, 40, 50], size=3, replace=False)
print(sample)
A[20 40 50]
B[50 20 10]
C[10 20 30]
D[40 10 30]
Attempts:
2 left
💡 Hint
Remember that setting the seed fixes the random output.
data_output
intermediate
1:30remaining
Shape of random normal samples array
What is the shape of the array produced by this code?
import numpy as np
samples = np.random.normal(loc=5, scale=2, size=(4,3))
print(samples.shape)
NumPy
import numpy as np
samples = np.random.normal(loc=5, scale=2, size=(4,3))
print(samples.shape)
A(4, 3)
B(3, 4)
C(12,)
D(4,)
Attempts:
2 left
💡 Hint
The size parameter defines the shape of the output array.
visualization
advanced
2:30remaining
Histogram of uniform random samples
Which option shows the correct histogram plot for 1000 samples from a uniform distribution between 0 and 1?
NumPy
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
samples = np.random.uniform(0, 1, 1000)
plt.hist(samples, bins=10, edgecolor='black')
plt.show()
AHistogram with bars increasing from left to right
BHistogram with one tall bar at 0 and others near zero
CHistogram with a bell shape centered at 0.5
DHistogram with bars roughly equal height across bins
Attempts:
2 left
💡 Hint
Uniform distribution means equal chance for all values in the range.
🧠 Conceptual
advanced
1:30remaining
Effect of random seed on reproducibility
Why do we set a random seed before generating random samples in numpy?
ATo limit the range of random numbers generated
BTo ensure the random samples are the same every time the code runs
CTo speed up the random number generation
DTo make the samples more random
Attempts:
2 left
💡 Hint
Think about reproducibility in experiments.
🔧 Debug
expert
2:00remaining
Identify the error in random sample generation
What error does this code raise?
import numpy as np
np.random.seed(2)
sample = np.random.choice([1, 2, 3], size=5, replace=False)
print(sample)
NumPy
import numpy as np
np.random.seed(2)
sample = np.random.choice([1, 2, 3], size=5, replace=False)
print(sample)
ATypeError: 'replace' argument must be boolean
BSyntaxError: invalid syntax
CValueError: Cannot take a larger sample than population when 'replace=False'
DNo error, prints 5 unique samples
Attempts:
2 left
💡 Hint
Check if sample size is larger than population when replace=False.