0
0
NumPydata~10 mins

np.sum() and axis parameter 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 sum of all elements in the array.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
total = np.sum([1])
print(total)
Drag options to blanks, or click blank then click option'
Asum
Bnp
Carr
D[1, 2, 3, 4]
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the module name 'np' instead of the array.
Passing the function name 'sum' instead of the array.
Passing a list literal instead of the array variable.
2fill in blank
medium

Complete the code to calculate the sum of each column in the 2D array.

NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4]])
sums = np.sum(arr, axis=[1])
print(sums)
Drag options to blanks, or click blank then click option'
A-1
B1
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=1 to sum columns instead of rows.
Using an invalid axis number.
Omitting the axis parameter.
3fill in blank
hard

Fix the error in the code to sum each row in the 2D array.

NumPy
import numpy as np
arr = np.array([[5, 6, 7], [8, 9, 10]])
sums = np.sum(arr, axis=[1])
print(sums)
Drag options to blanks, or click blank then click option'
A1
B2
C0
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=0 to sum rows instead of columns.
Using an axis value that is out of range.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths as values, but only for words longer than 3 letters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if len(word) [2] 3}
print(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 instead of its length as the value.
Using '<' instead of '>' in the condition.
5fill in blank
hard

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

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