0
0
NumPydata~10 mins

Array protocol and __array__ 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 convert a custom object to a NumPy array using the array protocol.

NumPy
import numpy as np

class MyArray:
    def __array__(self):
        return np.array([1])

obj = MyArray()
result = np.array(obj)
print(result)
Drag options to blanks, or click blank then click option'
A[1, 2, 3]
B(1, 2, 3)
C{1, 2, 3}
D1, 2, 3
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a tuple or set may work but is less common and can cause unexpected behavior.
Returning multiple values without a container causes errors.
2fill in blank
medium

Complete the code to check if an object supports the array protocol by using np.asarray.

NumPy
import numpy as np

class Custom:
    def __array__(self):
        return np.array([10, 20, 30])

obj = Custom()
arr = np.asarray([1])
print(arr)
Drag options to blanks, or click blank then click option'
Aobj.__array__()
Bobj
C[10, 20, 30]
Dnp.array(obj)
Attempts:
3 left
💡 Hint
Common Mistakes
Calling __array__ manually inside np.asarray is redundant.
Passing a list instead of the object ignores the custom method.
3fill in blank
hard

Fix the error in the code by completing the __array__ method to return a NumPy array.

NumPy
import numpy as np

class Data:
    def __array__(self):
        [1]

obj = Data()
print(np.array(obj))
Drag options to blanks, or click blank then click option'
Areturn np.array([1, 2, 3])
Breturn [1, 2, 3]
Creturn (1, 2, 3)
Dreturn '123'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a list or tuple directly can cause unexpected behavior.
Returning a string is invalid and causes errors.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2]
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Clen(word) > 3
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as the value instead of its length.
Comparing the word string directly to a number causes errors.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths only if length is less than 5.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
result = [1]: [2] for w in words if [3]
print(result)
Drag options to blanks, or click blank then click option'
A{w.upper()}
Blen(w)
Clen(w) < 5
D{w}
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces incorrectly for keys.
Not converting words to uppercase.
Using wrong comparison operators.