Challenge - 5 Problems
Random Choice Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of numpy random choice with replacement
What is the output of this code snippet?
import numpy as np np.random.seed(0) arr = np.array([10, 20, 30, 40]) result = np.random.choice(arr, size=3, replace=True) print(result)
NumPy
import numpy as np np.random.seed(0) arr = np.array([10, 20, 30, 40]) result = np.random.choice(arr, size=3, replace=True) print(result)
Attempts:
2 left
💡 Hint
Remember that numpy.random.choice with replace=True can pick the same element multiple times.
✗ Incorrect
With seed 0, numpy.random.choice picks elements in a reproducible way. The output array is [40 10 10].
❓ data_output
intermediate2:00remaining
Number of unique elements in random choice without replacement
Given this code, how many unique elements will the result contain?
import numpy as np np.random.seed(1) arr = np.array([5, 10, 15, 20, 25]) result = np.random.choice(arr, size=4, replace=False) print(len(np.unique(result)))
NumPy
import numpy as np np.random.seed(1) arr = np.array([5, 10, 15, 20, 25]) result = np.random.choice(arr, size=4, replace=False) print(len(np.unique(result)))
Attempts:
2 left
💡 Hint
When replace=False, elements cannot repeat in the sample.
✗ Incorrect
Sampling 4 elements without replacement from 5 unique elements means all 4 are unique.
🔧 Debug
advanced2:00remaining
Identify the error in numpy random choice usage
What error does this code raise?
import numpy as np arr = np.array([1, 2, 3]) result = np.random.choice(arr, size=5, replace=False) print(result)
NumPy
import numpy as np arr = np.array([1, 2, 3]) result = np.random.choice(arr, size=5, replace=False) print(result)
Attempts:
2 left
💡 Hint
Check if the sample size is larger than the array length when replace=False.
✗ Incorrect
Sampling 5 elements without replacement from an array of length 3 is impossible, raising ValueError.
🚀 Application
advanced2:00remaining
Weighted random choice output
What is the output of this code?
import numpy as np np.random.seed(2) arr = np.array(['red', 'green', 'blue']) weights = [0.1, 0.7, 0.2] result = np.random.choice(arr, size=5, p=weights) print(result)
NumPy
import numpy as np np.random.seed(2) arr = np.array(['red', 'green', 'blue']) weights = [0.1, 0.7, 0.2] result = np.random.choice(arr, size=5, p=weights) print(result)
Attempts:
2 left
💡 Hint
Weights affect the probability of each element being chosen.
✗ Incorrect
With seed 2 and given weights, the output is ['green' 'green' 'green' 'blue' 'green'].
🧠 Conceptual
expert2:00remaining
Effect of random seed on numpy random choice
Which statement is true about setting a random seed before using numpy.random.choice?
Attempts:
2 left
💡 Hint
Think about reproducibility in random operations.
✗ Incorrect
Setting the seed fixes the random number generator state, making outputs reproducible.