Vectorization over loops in NumPy - Time & Space Complexity
We want to see how using vectorization instead of loops changes the time it takes to run code with numpy.
How does the work grow when we handle bigger data?
Analyze the time complexity of the following code snippet.
import numpy as np
n = 10 # Example value for n
arr = np.arange(n)
squared = arr * arr
This code creates an array of numbers and then squares each number using vectorized multiplication.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying each element in the array by itself.
- How many times: Once for each element in the array, all done together using vectorized operation.
As the array size grows, the time to square all elements grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to complete the operation grows linearly with the number of elements.
[X] Wrong: "Vectorized operations run instantly no matter the input size."
[OK] Correct: Vectorization speeds things up by doing many operations at once, but it still needs to process each element, so time grows with input size.
Understanding how vectorization changes time complexity helps you write faster code and explain your choices clearly in real projects.
"What if we replaced vectorized multiplication with a Python for-loop to square each element? How would the time complexity change?"
Practice
vectorization in numpy instead of loops?Solution
Step 1: Understand vectorization concept
Vectorization means applying operations on whole arrays at once, not one element at a time.Step 2: Compare speed and simplicity
This approach uses optimized numpy functions that run faster than explicit loops.Final Answer:
It makes the code run faster by doing many operations at once. -> Option AQuick Check:
Vectorization = faster code [OK]
- Thinking vectorization slows code
- Believing vectorization needs more code
- Confusing vectorization with loops
a?Solution
Step 1: Identify vectorized addition
Usingnp.add(a, 5, out=a)adds 5 to every element in arrayaefficiently.Step 2: Check other options
a + 5works but returns a new array,for i in a: i = i + 5does not changea, anda.append(5)is invalid for numpy arrays.Final Answer:
np.add(a, 5, out=a) -> Option CQuick Check:
np.add = vectorized add [OK]
- Using loops that don't modify array
- Trying list methods on numpy arrays
- Confusing array addition with append
import numpy as np arr = np.array([1, 2, 3]) result = arr * 2 print(result)
Solution
Step 1: Understand array multiplication
Multiplying a numpy array by a number multiplies each element by that number.Step 2: Calculate element-wise multiplication
Each element in[1, 2, 3]is multiplied by 2, resulting in[2, 4, 6].Final Answer:
[2 4 6] -> Option AQuick Check:
Array * number = element-wise multiply [OK]
- Thinking it concatenates arrays
- Expecting an error on multiplication
- Confusing element-wise with matrix multiply
arr using a loop:import numpy as np
arr = np.array([1, 2, 3])
for i in arr:
i = i + 10
print(arr)Solution
Step 1: Understand loop variable behavior
Variableiis a copy of each element, so changingidoes not changearr.Step 2: Explain why array remains unchanged
The original arrayarrstays the same because the loop does not assign back to array elements.Final Answer:
Loop variableidoes not modify original array elements. -> Option BQuick Check:
Loop var copy ≠ array change [OK]
- Assuming loop changes array automatically
- Thinking syntax error exists
- Believing numpy disallows int addition
data = np.array([1, 2, 3, 4, 5]). You want to create a new array where each element is squared if it is even, otherwise doubled. Which vectorized code achieves this?Solution
Step 1: Understand vectorized conditional with np.where
np.where(condition, x, y)returns array choosingxwhere condition is true, elsey.Step 2: Apply condition for even and odd elements
Conditiondata % 2 == 0checks even numbers; squares them, else doubles.Step 3: Check other options
[x**2 if x%2==0 else x*2 for x in data] uses list comprehension (not vectorized), C uses loop (not vectorized), D is invalid syntax.Final Answer:
np.where(data % 2 == 0, data**2, data*2) -> Option DQuick Check:
np.where = vectorized if-else [OK]
- Using loops or list comprehensions instead of vectorization
- Writing invalid syntax for conditional operations
- Confusing element-wise operations with scalar
Ready to prove it?
Pass the test and this pattern moves unknown
