Complete the code to convert a custom object to a NumPy array using the array protocol.
import numpy as np class MyArray: def __array__(self): return np.array([1]) obj = MyArray() result = np.array(obj) print(result)
The __array__ method should return a NumPy array or something that can be converted to one. Returning a list like [1, 2, 3] works correctly.
Complete the code to check if an object supports the array protocol by using np.asarray.
import numpy as np class Custom: def __array__(self): return np.array([10, 20, 30]) obj = Custom() arr = np.asarray([1]) print(arr)
__array__ manually inside np.asarray is redundant.np.asarray calls the __array__ method automatically if it exists. So passing the object directly is correct.
Fix the error in the code by completing the __array__ method to return a NumPy array.
import numpy as np class Data: def __array__(self): [1] obj = Data() print(np.array(obj))
The __array__ method must return a NumPy array. Returning np.array([1, 2, 3]) ensures this.
Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.
words = ['apple', 'bat', 'carrot', 'dog'] lengths = {word: [1] for word in words if [2] print(lengths)
The dictionary comprehension maps each word to its length using len(word). The condition filters words with length greater than 3 using len(word) > 3.
Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is less than 5.
words = ['apple', 'bat', 'carrot', 'dog'] result = [1]: [2] for w in words if [3] print(result)
The dictionary comprehension creates keys as uppercase words using w.upper(), values as their lengths with len(w), and filters words with length less than 5 using len(w) < 5.