Challenge - 5 Problems
Vectorized Operations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of vectorized addition vs loop addition
What is the output of the following code comparing vectorized addition with a loop?
Data Analysis Python
import numpy as np arr = np.array([1, 2, 3, 4]) result_vectorized = arr + 5 result_loop = [] for x in arr: result_loop.append(x + 5) print(result_vectorized) print(result_loop)
Attempts:
2 left
💡 Hint
Think about how numpy arrays handle addition compared to lists.
✗ Incorrect
The numpy array adds 5 to each element directly, producing [6 7 8 9]. The loop appends each element plus 5 to a list, resulting in [6, 7, 8, 9].
❓ data_output
intermediate2:00remaining
Resulting array shape after vectorized multiplication
Given the code below, what is the shape of the resulting array after vectorized multiplication?
Data Analysis Python
import numpy as np arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([10, 20]) result = arr1 * arr2 print(result.shape)
Attempts:
2 left
💡 Hint
Consider how numpy broadcasts the smaller array to match the larger array's shape.
✗ Incorrect
The array arr2 is broadcast across the rows of arr1, so the result keeps the shape (2, 2).
🔧 Debug
advanced2:00remaining
Identify the error in loop vs vectorized code
What error will the following code produce?
Data Analysis Python
import numpy as np arr = np.array([1, 2, 3]) result = [] for x in arr: result = result + x print(result)
Attempts:
2 left
💡 Hint
Check how list addition works with integers.
✗ Incorrect
The code tries to add an integer to a list using '+', which causes a TypeError because list concatenation requires another list.
🚀 Application
advanced2:00remaining
Performance difference between vectorized and loop sum
Which statement best describes the performance difference when summing a large array using vectorized numpy sum vs a Python loop?
Attempts:
2 left
💡 Hint
Think about how numpy is implemented under the hood.
✗ Incorrect
Numpy's vectorized operations use optimized compiled code, making them much faster than Python loops for large data.
🧠 Conceptual
expert2:00remaining
Why vectorized operations reduce memory overhead
Why do vectorized operations typically use less memory than equivalent Python loops when processing large datasets?
Attempts:
2 left
💡 Hint
Consider how numpy arrays store data compared to Python lists.
✗ Incorrect
Vectorized operations work on contiguous blocks of memory and avoid overhead of Python objects, reducing memory use.