0
0
NumPydata~20 mins

Avoiding temporary arrays in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Temporary Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[5 7 9]
B[4 10 18]
C[1 2 3]
D[4 5 6]
Attempts:
2 left
💡 Hint
Look at the use of the 'out' parameter in np.multiply.
data_output
intermediate
2: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
A0
B1
C2
D3
Attempts:
2 left
💡 Hint
Think about how numpy evaluates chained additions.
🔧 Debug
advanced
2: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)
ABecause x += y + z modifies x without any temporary arrays
BBecause numpy does not support in-place operations
CBecause in-place addition always creates a temporary array
DBecause y + z creates a temporary array before adding to x
Attempts:
2 left
💡 Hint
Look at the order of operations and what y + z does.
🚀 Application
advanced
2: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
A
np.add(x, y, out=x)
np.add(x, z, out=x)
result = x
Bresult = np.add(np.add(x, y), z)
Cresult = x + (y + z)
Dresult = np.add(x, y + z)
Attempts:
2 left
💡 Hint
Use the 'out' parameter to store results in-place.
🧠 Conceptual
expert
2:00remaining
Why avoid temporary arrays in large data computations?
Why is it important to avoid creating temporary arrays in large numpy computations?
ATo reduce memory usage and improve performance by minimizing data copying
BBecause temporary arrays cause syntax errors in numpy
CBecause numpy does not support temporary arrays for large data
DTo make code shorter and easier to read
Attempts:
2 left
💡 Hint
Think about memory and speed when working with big data.