Complete the code to create a NumPy array of shape (3, 1).
import numpy as np arr = np.array([[1], [2], [3]]) print(arr[1])
The .shape attribute shows the dimensions of the array. Here, it will print (3, 1).
Complete the code to add a 1D array to a 2D array using broadcasting.
import numpy as np A = np.array([[1, 2, 3], [4, 5, 6]]) B = np.array([10, 20, 30]) result = A [1] B print(result)
The + operator adds arrays element-wise. Broadcasting allows adding a 1D array to each row of a 2D array.
Fix the error in the code that tries to add arrays with incompatible shapes.
import numpy as np A = np.array([[1, 2, 3], [4, 5, 6]]) B = np.array([10, 20]) result = A + B.[1](2, 1) print(result)
flatten or ravel make B 1D, which is still incompatible.resize modifies in place and repeats elements if necessary, not suitable here.To fix the shape mismatch error, use B.reshape(2, 1) to make B shape (2, 1) which broadcasts correctly when added to A (2, 3).
Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.
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 length and filters words with length greater than 3 using >.
Fill all three blanks to create a dictionary of uppercase words and their lengths for words longer than 3 characters.
words = ['apple', 'bat', 'carrot', 'dog'] [1] = {word.[2](): [3] for word in words if len(word) > 3} print([1])
The code creates a dictionary named result. It uses word.upper() for keys and len(word) for values, filtering words longer than 3 characters.