0
0
NumPydata~10 mins

Type promotion in operations 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 create a NumPy array of integers.

NumPy
import numpy as np
arr = np.array([1, 2, 3], dtype="[1]")
print(arr.dtype)
Drag options to blanks, or click blank then click option'
Aint32
Bstr
Cfloat64
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using a float dtype when integers are needed.
Using string dtype which is not numeric.
2fill in blank
medium

Complete the code to add an integer array and a float array, showing type promotion.

NumPy
import numpy as np
arr_int = np.array([1, 2, 3], dtype='int32')
arr_float = np.array([1.0, 2.0, 3.0], dtype="[1]")
result = arr_int + arr_float
print(result.dtype)
Drag options to blanks, or click blank then click option'
Afloat32
Bint32
Cbool
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using int dtype for float array, which prevents promotion.
Using string dtype causing errors.
3fill in blank
hard

Fix the error in the code to correctly multiply an integer array by a float scalar with type promotion.

NumPy
import numpy as np
arr = np.array([1, 2, 3], dtype='int16')
scalar = [1]
result = arr * scalar
print(result.dtype)
Drag options to blanks, or click blank then click option'
A'2'
B2
C2.0
DTrue
Attempts:
3 left
💡 Hint
Common Mistakes
Using integer scalar which does not promote type.
Using string scalar causing 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 = ['data', 'science', 'ai', 'ml']
lengths = {word: [1] for word in words if [2] > 3}
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Blen(words)
Cword
Dlen(word) > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using len(words) which is total list length.
Using word instead of length for filtering.
5fill in blank
hard

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

NumPy
words = ['cat', 'dog', 'a', 'bird']
[1] = {word.[2](): [3] for word in words if len(word) > 2}
print(result)
Drag options to blanks, or click blank then click option'
Aresult
Bupper
Clen(word)
Dlower
Attempts:
3 left
💡 Hint
Common Mistakes
Using lower() instead of upper().
Not assigning the comprehension to a variable.