Challenge - 5 Problems
Cumulative Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Think about adding each element to the sum of all previous elements.
✗ Incorrect
The np.cumsum() function returns the cumulative sum of the elements along a given axis. For the array [1, 2, 3, 4], the cumulative sums are:
- 1
- 1 + 2 = 3
- 3 + 3 = 6
- 6 + 4 = 10
❓ data_output
intermediate2: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)
Attempts:
2 left
💡 Hint
Cumulative sum along axis 0 adds values down each column.
✗ Incorrect
Applying np.cumsum() along axis 0 sums elements down each column:
- First row stays the same: [1, 2]
- Second row: [1+3=4, 2+4=6]
- Third row: [4+5=9, 6+6=12]
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Check the shape and dimensions of the array and the axis parameter.
✗ Incorrect
The array is 1-dimensional, so axis 1 does not exist. Using axis=1 causes an AxisError.
🚀 Application
advanced2: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)
Attempts:
2 left
💡 Hint
Add each day's sales to the sum of all previous days.
✗ Incorrect
The running total sums sales day by day:
- Day 1: 100
- Day 2: 100 + 200 = 300
- Day 3: 300 + 150 = 450
- Day 4: 450 + 300 = 750
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
Consider how cumulative sum works and the range of int8.
✗ Incorrect
The cumulative sum adds values normally. Since the sum 6 fits in int8 range (-128 to 127), the output is [1, 3, 6].