0
0
NumPydata~20 mins

np.cumsum() for cumulative sum in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Cumulative Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.cumsum() on a 1D array
What is the output of the following code using np.cumsum()?
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
cum_sum = np.cumsum(arr)
print(cum_sum)
A[1 3 6 10]
B[1 2 3 4]
C[10 9 7 4]
D[1 4 9 16]
Attempts:
2 left
💡 Hint
Think about adding each element to the sum of all previous elements.
data_output
intermediate
2:00remaining
Cumulative sum along axis in 2D array
What is the output of np.cumsum() when applied along axis 0 on this 2D array?
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
cum_sum = np.cumsum(arr, axis=0)
print(cum_sum)
A
[[1 2]
 [3 4]
 [5 6]]
B
[[1 2]
 [4 6]
 [9 12]]
C
[[1 5 10]
 [2 6 12]]
D
[[1 3]
 [2 4]
 [5 6]]
Attempts:
2 left
💡 Hint
Cumulative sum along axis 0 adds values down each column.
🔧 Debug
advanced
2:00remaining
Identify the error in np.cumsum usage
What error will this code raise?
NumPy
import numpy as np
arr = np.array([1, 2, 3])
cum_sum = np.cumsum(arr, axis=1)
print(cum_sum)
ANo error, outputs [1 3 6]
BValueError: operands could not be broadcast together
CAxisError: axis 1 is out of bounds for array of dimension 1
DTypeError: cumsum() got an unexpected keyword argument 'axis'
Attempts:
2 left
💡 Hint
Check the shape and dimensions of the array and the axis parameter.
🚀 Application
advanced
2:00remaining
Using np.cumsum() to calculate running totals
You have daily sales data: [100, 200, 150, 300]. Which option shows the running total of sales using np.cumsum()?
NumPy
import numpy as np
sales = np.array([100, 200, 150, 300])
running_total = np.cumsum(sales)
print(running_total)
A[100 300 350 650]
B[100 200 150 300]
C[100 250 400 700]
D[100 300 450 750]
Attempts:
2 left
💡 Hint
Add each day's sales to the sum of all previous days.
🧠 Conceptual
expert
2:00remaining
Effect of np.cumsum() with different data types
Given arr = np.array([1, 2, 3], dtype='int8'), what is the output of np.cumsum(arr)?
NumPy
import numpy as np
arr = np.array([1, 2, 3], dtype='int8')
cum_sum = np.cumsum(arr)
print(cum_sum)
A[1 3 6]
B[1 3 -127]
C[1 3 5]
D[1 2 3]
Attempts:
2 left
💡 Hint
Consider how cumulative sum works and the range of int8.