Bird
Raised Fist0
NumPydata~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What does np.random.default_rng() do in NumPy?
easy
A. Creates a modern random number generator instance
B. Generates a fixed list of numbers
C. Imports the NumPy library
D. Sorts an array in ascending order

Solution

  1. Step 1: Understand the function purpose

    np.random.default_rng() creates a new random number generator object using the modern Generator API.
  2. Step 2: Compare with other options

    It does not generate fixed lists, import libraries, or sort arrays.
  3. Final Answer:

    Creates a modern random number generator instance -> Option A
  4. Quick Check:

    default_rng() = modern RNG instance [OK]
Hint: Remember default_rng() always creates a new RNG object [OK]
Common Mistakes:
  • Confusing it with random number generation output
  • Thinking it imports NumPy
  • Mixing it up with sorting functions
2. Which of the following is the correct way to create a random number generator with a seed of 42 using np.random.default_rng()?
easy
A. rng = np.random.default_rng(42, seed=42)
B. rng = np.random.default_rng(42)
C. rng = np.random.default_rng().seed(42)
D. rng = np.random.default_rng().random(42)

Solution

  1. Step 1: Check the correct syntax for seeding

    The seed is passed as an argument directly to default_rng(), so np.random.default_rng(42) is correct.
  2. Step 2: Evaluate other options

    rng = np.random.default_rng(42, seed=42) is invalid because it passes seed both positionally and as keyword, causing TypeError: multiple values for 'seed'. rng = np.random.default_rng().seed(42) tries to call seed() method which does not exist on the Generator. rng = np.random.default_rng().random(42) calls random(42) which generates numbers, not seeds.
  3. Final Answer:

    rng = np.random.default_rng(42) -> Option B
  4. Quick Check:

    Seed passed as argument = rng = np.random.default_rng(42) [OK]
Hint: Pass seed directly inside default_rng() parentheses [OK]
Common Mistakes:
  • Passing seed both positionally and as keyword argument
  • Calling seed() method on the generator
  • Confusing random() method with seeding
3. What is the output of this code?
import numpy as np
rng = np.random.default_rng(123)
print(rng.integers(1, 10, size=3))
medium
A. [3 3 7]
B. [3 1 7]
C. [2 3 7]
D. [3 3 6]

Solution

  1. Step 1: Understand the code

    The code creates a random number generator with seed 123, then generates 3 random integers between 1 (inclusive) and 10 (exclusive).
  2. Step 2: Run the code or recall output

    Running this code produces the array [3 3 7].
  3. Final Answer:

    [3 3 7] -> Option A
  4. Quick Check:

    Seed 123 + integers(1,10,3) = [3 3 7] [OK]
Hint: Seed fixes output; integers(1,10,3) gives same 3 numbers [OK]
Common Mistakes:
  • Assuming inclusive upper bound 10
  • Confusing seed effect on output
  • Mixing output with floats instead of integers
4. Identify the error in this code snippet:
import numpy as np
rng = np.random.default_rng()
random_numbers = rng.random(5, seed=10)
print(random_numbers)
medium
A. random() should be called without parentheses
B. default_rng() requires a seed argument
C. random() does not accept a seed argument
D. rng.random() returns integers, not floats

Solution

  1. Step 1: Check method signature of random()

    The random() method of the Generator does not accept a seed parameter; seeding is done when creating the generator.
  2. Step 2: Identify the error

    Passing seed=10 to random() causes a TypeError.
  3. Final Answer:

    random() does not accept a seed argument -> Option C
  4. Quick Check:

    Seed only in default_rng(), not in random() [OK]
Hint: Seed only when creating RNG, not in random() calls [OK]
Common Mistakes:
  • Trying to seed random() method
  • Thinking random() returns integers
  • Believing default_rng() needs seed always
5. You want to generate a reproducible shuffled version of the list [10, 20, 30, 40, 50] using np.random.default_rng(). Which code correctly achieves this?
hard
A. rng = np.random.default_rng(7) arr = [10, 20, 30, 40, 50] rng.shuffle(arr) print(arr)
B. rng = np.random.default_rng() arr = [10, 20, 30, 40, 50] rng.shuffle(arr) print(arr)
C. rng = np.random.default_rng(7) arr = [10, 20, 30, 40, 50] shuffled = np.random.shuffle(arr) print(shuffled)
D. rng = np.random.default_rng(7) arr = [10, 20, 30, 40, 50] shuffled = rng.permutation(arr) print(shuffled)

Solution

  1. Step 1: Understand reproducible shuffling

    To get reproducible shuffling, seed the generator and use its methods. rng.shuffle() shuffles in-place and returns None, while rng.permutation() returns a shuffled copy.
  2. Step 2: Analyze options

    rng = np.random.default_rng(7) arr = [10, 20, 30, 40, 50] rng.shuffle(arr) print(arr) fails because rng.shuffle() requires a NumPy ndarray but arr is a list (TypeError). rng = np.random.default_rng() arr = [10, 20, 30, 40, 50] rng.shuffle(arr) print(arr) has no seed, so not reproducible (also fails on list). rng = np.random.default_rng(7) arr = [10, 20, 30, 40, 50] shuffled = np.random.shuffle(arr) print(shuffled) incorrectly uses np.random.shuffle() which ignores rng, requires ndarray (fails on list), and returns None. rng = np.random.default_rng(7) arr = [10, 20, 30, 40, 50] shuffled = rng.permutation(arr) print(shuffled) seeds and uses permutation() to get a reproducible shuffled copy.
  3. Final Answer:

    rng = np.random.default_rng(7) arr = [10, 20, 30, 40, 50] shuffled = rng.permutation(arr) print(shuffled) -> Option D
  4. Quick Check:

    Seed + permutation() = reproducible shuffled copy [OK]
Hint: Use rng.permutation(arr) with seed for reproducible shuffle [OK]
Common Mistakes:
  • Using np.random.shuffle() ignoring seed
  • Expecting shuffle() to return a new list
  • Not seeding the generator for reproducibility