Challenge - 5 Problems
Temporary Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of element-wise multiplication without temporary arrays
What is the output of this code that multiplies two numpy arrays element-wise without creating a temporary array?
NumPy
import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) result = np.multiply(x, y, out=x) print(result)
Attempts:
2 left
💡 Hint
Look at the use of the 'out' parameter in np.multiply.
✗ Incorrect
The 'out=x' argument tells numpy to store the result directly in array x, avoiding a temporary array. So x becomes [4, 10, 18].
❓ data_output
intermediate2:00remaining
Number of temporary arrays created in chained operations
Given the code below, how many temporary arrays are created during the computation?
NumPy
import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) z = np.array([7, 8, 9]) result = x + y + z
Attempts:
2 left
💡 Hint
Think about how numpy evaluates chained additions.
✗ Incorrect
The expression x + y + z is evaluated as (x + y) + z. The first addition creates one temporary array, then adding z creates another temporary array before assigning to result. So 2 temporary arrays are created.
🔧 Debug
advanced2:00remaining
Why does this code create a temporary array?
Consider this code snippet. Why does it create a temporary array despite using in-place addition?
NumPy
import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) z = np.array([7, 8, 9]) x += y + z print(x)
Attempts:
2 left
💡 Hint
Look at the order of operations and what y + z does.
✗ Incorrect
The expression y + z creates a temporary array holding their sum before x is updated in-place. So a temporary array is created despite using '+='.
🚀 Application
advanced2:00remaining
Rewrite code to avoid temporary arrays
Which option rewrites the code below to avoid creating temporary arrays during the addition of three arrays?
NumPy
import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) z = np.array([7, 8, 9]) result = x + y + z
Attempts:
2 left
💡 Hint
Use the 'out' parameter to store results in-place.
✗ Incorrect
Option A uses np.add with the 'out' parameter to store intermediate results in x, avoiding temporary arrays. Other options create temporary arrays during addition.
🧠 Conceptual
expert2:00remaining
Why avoid temporary arrays in large data computations?
Why is it important to avoid creating temporary arrays in large numpy computations?
Attempts:
2 left
💡 Hint
Think about memory and speed when working with big data.
✗ Incorrect
Temporary arrays use extra memory and slow down computations due to copying data. Avoiding them helps performance and reduces memory pressure.