Random choice from array in NumPy - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time it takes to pick a random item from an array changes as the array grows.
How does the size of the array affect the speed of choosing a random element?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.arange(1000)
choice = np.random.choice(arr)
print(choice)
This code creates an array of numbers from 0 to 999 and picks one random number from it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing one random index in the array.
- How many times: Exactly once per call.
Picking one random element does not require checking all elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter how big the array is.
Time Complexity: O(1)
This means picking a random element takes the same amount of time no matter how large the array is.
[X] Wrong: "Choosing a random element takes longer if the array is bigger because it has more items to look through."
[OK] Correct: The method directly picks an index without scanning the whole array, so the size does not affect the time.
Understanding constant time operations like random choice helps you explain efficient data access in real projects.
"What if we wanted to pick multiple random elements without replacement? How would the time complexity change?"
Practice
What does the numpy.random.choice function do?
Solution
Step 1: Understand the function purpose
numpy.random.choiceis used to select random elements from an array.Step 2: Compare with other options
Sorting, calculating mean, or removing duplicates are different functions and unrelated to random choice.Final Answer:
It picks one or more random elements from an array. -> Option AQuick Check:
Random choice = pick random elements [OK]
- Confusing random choice with sorting
- Thinking it calculates statistics like mean
- Assuming it removes duplicates
Which of the following is the correct syntax to pick 3 random elements from a numpy array arr with replacement?
import numpy as np arr = np.array([10, 20, 30, 40, 50])
Solution
Step 1: Check correct parameter names
The function usessizeto specify number of elements andreplaceto allow repeats.Step 2: Validate each option
np.random.choice(arr, size=3, replace=True) uses correct parameters:size=3andreplace=True. Others have wrong parameter names or extra invalid ones.Final Answer:
np.random.choice(arr, size=3, replace=True) -> Option CQuick Check:
Correct syntax = size=3, replace=True [OK]
- Using positional argument without size=
- Setting replace=False when repeats are needed
- Adding invalid parameters like axis
What is the output of this code?
import numpy as np np.random.seed(0) arr = np.array([1, 2, 3, 4, 5]) result = np.random.choice(arr, size=4, replace=False) print(result)
Solution
Step 1: Understand seed and choice without replacement
Setting seed ensures reproducible random results. Choosing 4 unique elements without replacement picks 4 different values from arr.Step 2: Run code or recall output
With seed 0, the output is[2 5 1 4].Final Answer:
[2 5 1 4] -> Option DQuick Check:
Seed 0 + replace=False = [2 5 1 4] [OK]
- Ignoring seed and expecting different output
- Confusing replace=True and replace=False results
- Assuming output is sorted
Identify the error in this code snippet:
import numpy as np arr = np.array([1, 2, 3]) result = np.random.choice(arr, size=5, replace=False) print(result)
Solution
Step 1: Check size vs array length with replace=False
Choosing 5 elements without replacement from an array of length 3 is invalid and raises an error.Step 2: Confirm other parts are correct
Array is defined, numpy is imported, and replace parameter is valid. The main issue is size too large without replacement.Final Answer:
Size is larger than array length without replacement, causing an error. -> Option AQuick Check:
Size > array length + replace=False = error [OK]
- Ignoring size vs array length mismatch
- Assuming replace=True by default
- Not importing numpy before use
You have a numpy array data = np.array([10, 20, 30, 40, 50]). You want to randomly select 3 unique elements but ensure the number 20 is always included in the result. Which approach is correct?
Solution
Step 1: Understand the requirement
We want 3 unique elements including 20 always.Step 2: Choose method to guarantee 20
Remove 20, pick 2 unique elements from remaining, then add 20 to result ensures 20 is included and no duplicates.Step 3: Evaluate other options
Direct random choice may exclude 20. Picking with replacement can cause duplicates or exclude 20. Adding 20 manually after picking with replacement may cause duplicates.Final Answer:
Remove 20 from array, pick 2 without replacement, then add 20 back. -> Option BQuick Check:
Guarantee element by picking rest then adding it [OK]
- Assuming random choice always includes 20
- Using replacement causing duplicates
- Adding 20 after picking with replacement causing repeats
