Complete the code to calculate the sum of all elements in the array.
import numpy as np arr = np.array([1, 2, 3, 4]) total = np.sum([1]) print(total)
We use np.sum(arr) to add all elements in the array arr.
Complete the code to calculate the sum of each column in the 2D array.
import numpy as np arr = np.array([[1, 2], [3, 4]]) sums = np.sum(arr, axis=[1]) print(sums)
Using axis=1 sums across columns for each row, giving the sum of each row's elements.
But since we want the sum of each column, we use axis=0.
However, the question asks for sum of each column, so the correct axis is 0.
Fix the error in the code to sum each row in the 2D array.
import numpy as np arr = np.array([[5, 6, 7], [8, 9, 10]]) sums = np.sum(arr, axis=[1]) print(sums)
To sum each row, we sum across columns, which is axis=1.
Fill both blanks to create a dictionary with words as keys and their lengths as values, but only for words longer than 3 letters.
words = ['apple', 'bat', 'carrot', 'dog'] lengths = {word: [1] for word in words if len(word) [2] 3} print(lengths)
The dictionary comprehension uses len(word) to get the length, and the condition len(word) > 3 to filter words longer than 3 letters.
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.
words = ['apple', 'bat', 'carrot', 'dog'] lengths = { [1]: [2] for word in words if len(word) [3] 3 } print(lengths)
The dictionary comprehension uses word.upper() as keys, len(word) as values, and filters words with length greater than 3 using >.