Random data generation in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we generate random data, we want to know how long it takes as we ask for more data.
We ask: How does the time grow when we create more random items?
Analyze the time complexity of the following code snippet.
import random
def generate_random_list(n):
result = []
for _ in range(n):
result.append(random.randint(1, 100))
return result
This code creates a list of n random numbers between 1 and 100.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that runs
ntimes to add random numbers. - How many times: Exactly once for each number requested, so
ntimes.
Each time we ask for one more random number, the work grows by one step.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 random picks and adds |
| 100 | About 100 random picks and adds |
| 1000 | About 1000 random picks and adds |
Pattern observation: The work grows directly with the number of items requested.
Time Complexity: O(n)
This means the time to generate random data grows in a straight line as you ask for more numbers.
[X] Wrong: "Generating random numbers is instant and does not depend on how many we want."
[OK] Correct: Each random number takes a small amount of time, so more numbers mean more total time.
Understanding how time grows with data size helps you write efficient code and explain your thinking clearly in interviews.
"What if we generated random numbers inside a nested loop? How would the time complexity change?"
Practice
random.randint(a, b) function do in Python?Solution
Step 1: Understand the function purpose
random.randint(a, b)generates a random integer between two given numbers a and b, inclusive.Step 2: Compare options with function behavior
Returns a random integer N such that a ≤ N ≤ b correctly describes this behavior. Options A, C, and D describe other functions likerandom.uniform,random.choice, andrandom.shuffle.Final Answer:
Returns a random integer N such that a ≤ N ≤ b -> Option BQuick Check:
random.randint = random integer in range [OK]
- Confusing randint with random float functions
- Thinking randint returns a list element
- Mixing up randint with shuffle
random module and use choice to pick a random element from a list items?Solution
Step 1: Check import syntax
To usechoice, you must import therandommodule fully or importchoicespecifically. import random; random.choice(items) imports the module correctly.Step 2: Verify function usage
import random; random.choice(items) callsrandom.choice(items), which is correct. from random import randint; choice(items) importsrandintbut tries to callchoicewithout import. import random.choice; choice(items) has invalid import syntax. import random; random.randint(items) callsrandintwith a list, which is incorrect.Final Answer:
import random; random.choice(items) -> Option AQuick Check:
Correct import and call = import random; random.choice(items) [OK]
- Importing wrong functions
- Calling functions without module prefix
- Using randint instead of choice
import random items = ['apple', 'banana', 'cherry'] random.shuffle(items) print(items)
Solution
Step 1: Understand random.shuffle behavior
random.shufflerearranges the list elements in place randomly. It does not return a new list.Step 2: Analyze the print output
After shuffling, printingitemsshows the same list but with elements in random order. So output is a shuffled list, not the original order or a single item.Final Answer:
A randomly shuffled list of the original items -> Option DQuick Check:
shuffle changes list order in place [OK]
- Expecting shuffle to return a new list
- Thinking shuffle picks one random item
- Assuming list order stays same
import random items = ['red', 'green', 'blue'] print(random.choice(items, 1))
Solution
Step 1: Check random.choice function signature
random.choicetakes exactly one argument: a sequence (like a list). It returns one random element.Step 2: Identify the error cause
The code passes two arguments (itemsand1), which is invalid and causes a TypeError.Final Answer:
random.choice does not take two arguments -> Option CQuick Check:
choice takes one argument only [OK]
- Passing extra arguments to choice
- Thinking choice returns multiple items
- Confusing choice with sample
Solution
Step 1: Understand dictionary comprehension syntax
We want keys as numbers 1 to 5 and values as random integers between 10 and 20. The syntax is {key: value for key in iterable}.Step 2: Check each option
import random result = {i: random.randint(10, 20) for i in range(1, 6)} correctly usesias key andrandom.randint(10, 20)as value for each i in 1 to 5.
import random result = {random.randint(10, 20): i for i in range(1, 6)} swaps keys and values incorrectly.
import random result = {i: random.choice(range(10, 20)) for i in range(1, 6)} usesrandom.choice(range(10, 20))which produces integers 10-19 excluding 20, unlike randint(10,20).
import random result = dict(random.randint(10, 20) for i in range(1, 6)) tries to convert a generator of integers to dict, which causes an error.Final Answer:
import random result = {i: random.randint(10, 20) for i in range(1, 6)} -> Option AQuick Check:
Correct dict comprehension with randint [OK]
- Swapping keys and values
- Using dict() on generator of ints
- Using choice with range(10,20) excludes 20
