0
0
NumPydata~10 mins

np.cumsum() for cumulative sum in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to calculate the cumulative sum of the array using numpy.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
cum_sum = np.[1](arr)
print(cum_sum)
Drag options to blanks, or click blank then click option'
Acumsum
Bsum
Ccumprod
Dmean
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.sum() which returns the total sum, not cumulative sums.
Using np.cumprod() which calculates cumulative product instead.
2fill in blank
medium

Complete the code to calculate the cumulative sum along axis 0 of the 2D array.

NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
cum_sum_axis0 = np.cumsum(arr, axis=[1])
print(cum_sum_axis0)
Drag options to blanks, or click blank then click option'
A1
B0
C2
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=1 which sums along columns instead of rows.
Using axis=2 which is invalid for 2D arrays.
3fill in blank
hard

Fix the error in the code to correctly compute the cumulative sum of the list.

NumPy
import numpy as np
lst = [5, 10, 15]
cum_sum = np.cumsum([1])
print(cum_sum)
Drag options to blanks, or click blank then click option'
Anp.array(lst)
Blst
Clist(lst)
Dnp.sum(lst)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the list directly without conversion.
Using np.sum which returns total sum, not cumulative sums.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their cumulative sum of lengths as values for words longer than 3 letters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
cum_lengths = {word: [1] for word in words if len(word) [2] 3}
print(cum_lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<=
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as value instead of length.
Using wrong comparison operator like '<='.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys and their lengths as values for words longer than 3 letters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
result = { [1]: [2] for word in words if len(word) [3] 3 }
print(result)
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
C>
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using original word as key instead of uppercase.
Using wrong comparison operator.
Swapping keys and values.